﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml;
using CustomControl;
using Microsoft.Windows.Controls;
using TeacherLeftHand.DocEditor;
using TeacherLeftHand.Model;
using TeacherLeftHand.Util;
using log4net;
using TeacherLeftHand.DataAccess;
using TeacherLeftHand.ViewModel;
using MS.WindowsAPICodePack.Internal;
using Microsoft.Windows.Controls.Ribbon;
using Microsoft.WindowsAPICodePack.Taskbar;
using Microsoft.WindowsAPICodePack.Dialogs;
using Keyboard = System.Windows.Input.Keyboard;
using TeacherLeftHand.View;
using System.Windows.Markup;
using GalaSoft.MvvmLight.Messaging;
using TeacherLeftHand.Messages;
using Clipboard = System.Windows.Clipboard;
using ColorDialog = ColorPicker.ColorDialog;
using ContextMenu = System.Windows.Controls.ContextMenu;
using FlowDirection = System.Windows.FlowDirection;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MenuItem = System.Windows.Controls.MenuItem;
using MessageBox = System.Windows.MessageBox;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using Table = System.Windows.Documents.Table;
using TeacherLeftHand.Properties;
using DatePicker = System.Windows.Controls.DatePicker;
using WindowState = System.Windows.WindowState;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
    private DocumentTab SelectedDocument = null;


    #region Constants
    private const int MAX_TAB = 5;
    private const int MAX_RECENT_FILES = 13;

    #endregion

    #region Properties

    private ProgressBarWindow progressBarWindow = null;
    protected static readonly ILog Log = LogManager.GetLogger(typeof(MainWindow));
    //private TeachingPlanAccessor _teachingPlanAccessor;
    private int autoGenTabNumber = 1;
    private string _strLanguage;
    private List<string> filePaths = new List<string>();

    #endregion

    #region Main Window


    public MainWindow()
    {

        //Contruct KnowledgeItemView and set to Collapse

        Initialized += MainWindow_Initialized;
        Loaded += MainWindow_Loaded;
        Activated += MainWindow_Activated;
        KeyDown += MainWindow_KeyDown;
        Closing += MainWindow_Closing;
        InitializeComponent();

        layoutTeachingPlan.DataContext = ViewModelLocator.TeachingPlanStatic;
        Closed += (s, e) => ViewModelLocator.Cleanup();

        //_teachingPlanAccessor = new TeachingPlanAccessor();

        //regiser message
        Messenger.Default.Register<NewWindowMessage>(this, OpenCreateNewWindow);

        _strLanguage = cmbLanguage.SelectedValue.ToString();

        Loaded += DoubleClick;
    }

    #endregion

    void DoubleClick(object sender, RoutedEventArgs e)
    {
        try
        {
            if (System.Windows.Application.Current.Properties["PathFile"] != null)
            {

                string fname = System.Windows.Application.Current.Properties["PathFile"].ToString();

                // Act on the file...

                //MessageBox.Show(fname);
                //LoadFile(fname);
                string name = Path.GetFileName(fname);
                NewDocument(name);
                if(SelectedDocument.Editor.LoadDocument(fname))
                {
                    SelectedDocument.Editor.teachingPlan.FileChanged = false;
                    if (!Settings.Default.Options_RecentFiles.Contains(SelectedDocument.Editor.DocumentName))
                    {
                        Settings.Default.Options_RecentFiles.Add(SelectedDocument.Editor.DocumentName);
                    }    
                }else
                {
                    CloseDocument(SelectedDocument);
                }

            }
        }catch(Exception ex)
        {
            MessageBox.Show("Can not read this file!");
        }
        
        //else
        //{
        //    MessageBox.Show("ko co file");
        //}

    }

    private void OpenCreateNewWindow(NewWindowMessage msg)
    {
        if (msg.Action.Equals(WindowAction.Close)) return;

        if (msg.ItemType is KnowledgeItem)
        {
            var createNewKI = new CreateNewKIView();
            createNewKI.Owner = this;
            createNewKI.ShowDialog();
        }
        else if (msg.ItemType is TeachingMethod)
        {
            if (msg.Action.Equals(WindowAction.OpenCreate))
            {
                var createNewTM = new CreateNewTMView();
                createNewTM.Owner = this;
                createNewTM.ShowDialog();
            }
            else
            {
                var createNewTM = new CreateNewTMView(msg.ItemType as TeachingMethod);
                createNewTM.Owner = this;
                createNewTM.ShowDialog();
            }
        }
    }

    #region Reuseable Code

    #region Document



    public void NewDocument(string title)
    {
        if (TabCell.Items.Count > 0)
        {
            SelectedDocument.IsSelected = false;
        }
        var documentTab = new DocumentTab(title, false);
        var num = TabCell.Items.Count;
        if (num < MAX_TAB)
        {
            TabCell.Items.Add(documentTab);
            //ResizeTabs(TabCell); 
            documentTab.IsSelected = true;
            SelectedDocument.Editor.editor.Focus();
            SelectedDocument.Editor.teachingPlan.FileChanged = false;
            if (CoreHelpers.RunningOnWin7)
            {
                var tab = new TabbedThumbnail(this, documentTab.Editor, new Vector(0, 0));
                tab.SetWindowIcon(My.Resources.Resources.open16);
                tab.Title = documentTab.DocName;
                tab.TabbedThumbnailActivated += PreviewTabbedThumbnailActivated;
                tab.TabbedThumbnailClosed += preview_TabbedThumbnailClosed;
                tab.TabbedThumbnailMaximized += PreviewTabbedThumbnailMaximized;
                tab.TabbedThumbnailMinimized += PreviewTabbedThumbnailMinimized;
                TaskbarManager.Instance.TabbedThumbnail.AddThumbnailPreview(tab);
            }
            UpdateButtons(this, null);
        }
        else
        {
            MessageBox.Show(_strLanguage.Equals("en-US") ? "Can not create more tab" : "Không thể tạo thêm trang mới");
        }
    }

    //public void NewBlankDocument(string title)
    //{
    //    if (TabCell.Items.Count > 0)
    //    {
    //        SelectedDocument.IsSelected = false;
    //    }
    //    var documentTab = new DocumentTab(title, true);
    //    var num = TabCell.Items.Count;
    //    if (num < MAX_TAB)
    //    {
    //        TabCell.Items.Add(documentTab);
    //        //ResizeTabs(TabCell); 
    //        documentTab.IsSelected = true;
    //        SelectedDocument.Editor.editor.Focus();
    //        SelectedDocument.Editor.teachingPlan.FileChanged = false;
    //        if (CoreHelpers.RunningOnWin7)
    //        {
    //            var tab = new TabbedThumbnail(this, documentTab.Editor, new Vector(0, 0));
    //            tab.SetWindowIcon(My.Resources.Resources.open16);
    //            tab.Title = documentTab.DocName;
    //            tab.TabbedThumbnailActivated += PreviewTabbedThumbnailActivated;
    //            tab.TabbedThumbnailClosed += preview_TabbedThumbnailClosed;
    //            tab.TabbedThumbnailMaximized += PreviewTabbedThumbnailMaximized;
    //            tab.TabbedThumbnailMinimized += PreviewTabbedThumbnailMinimized;
    //            TaskbarManager.Instance.TabbedThumbnail.AddThumbnailPreview(tab);
    //        }
    //        UpdateButtons(this, null);
    //    }
    //    else
    //    {
    //        MessageBox.Show(_strLanguage.Equals("en-US") ? "Can not create more tab" : "Không thể tạo thêm trang mới");
    //    }
    //}
    private void CloseDocument(DocumentTab file)
    {
        if (CoreHelpers.RunningOnWin7)
        {
            var tab = TaskbarManager.Instance.TabbedThumbnail.GetThumbnailPreview(file.Editor);
            if (TaskbarManager.Instance.TabbedThumbnail.IsThumbnailPreviewAdded(tab))
            {
                tab.TabbedThumbnailActivated -= PreviewTabbedThumbnailActivated;
                tab.TabbedThumbnailClosed -= preview_TabbedThumbnailClosed;
                tab.TabbedThumbnailMaximized -= PreviewTabbedThumbnailMaximized;
                tab.TabbedThumbnailMinimized -= PreviewTabbedThumbnailMinimized;
                TaskbarManager.Instance.TabbedThumbnail.RemoveThumbnailPreview(file.Editor);
            }
        }
        //this.mainDockPanel.Children.Remove(file);
        TabCell.SelectedIndex = TabCell.Items.Count - 2;
        TabCell.Items.Remove(file);



        //ResizeTabs(TabCell);
    }

    //public CommonFileDialogFilterCollection GetOpenDialogFilters(CommonOpenFileDialog dialog)
    //{
    //    var f = dialog.Filters;
    //    var SupportedFiles = new CommonFileDialogFilter("Supported Documents", "*.rtf;*.txt");
    //    var FlowDocumentFiles = new CommonFileDialogFilter("FlowDocument", "*.xaml");//hainhCheck
    //    var HtmlFiles = new CommonFileDialogFilter("Html Document", "*.html;*.htm");//hainhCheck
    //    var RichTextFiles = new CommonFileDialogFilter("Rich Text Document", "*.rtf");
    //    var PlanTextFiles = new CommonFileDialogFilter("Plan Text Document", "*.txt");
    //    var AllFiles = new CommonFileDialogFilter("All Files", "*.*");
    //    f = dialog.Filters;
    //    f.Add(SupportedFiles);
    //    f.Add(FlowDocumentFiles);
    //    f.Add(HtmlFiles);
    //    f.Add(RichTextFiles);
    //    f.Add(PlanTextFiles);
    //    f.Add(AllFiles);
    //    return f;
    //}

    #endregion

    //public void ResizeTabs(TabControl tab)
    //{
    //    if (Settings.Default.Options_Tabs_SizeMode == 0)
    //    {
    //        foreach (DocumentTab i in tab.Items)
    //        {
    //            if (TabCell.Items.Count > 8)
    //            {
    //                var d = new double();
    //                var d2 = new double();
    //                d = TabCell.ActualWidth - 8;
    //                d2 = TabCell.Items.Count * 2;
    //                i.Width = d / d2;
    //            }
    //            else
    //            {
    //                var d = new double();
    //                d = tab.ActualWidth;
    //                i.Width = d / 8;
    //            }
    //        }
    //    }
    //}


    #region -RibbonBar

    private void UpdateSelected()
    {
        //if (SelectedDocument.Editor.teachingPlan.FileChanged)
        //{
        //    Title = SelectedDocument.DocName + " * - " + My.MyWpfExtension.Application.Info.ProductName;
        //    ((DocumentTab) TabCell.SelectedItem).HeaderContent.TabTitle.Visibility = Visibility.Collapsed;
        //    ((DocumentTab)TabCell.SelectedItem).HeaderContent.TabTitleFileChanged.Content = ((DocumentTab)TabCell.SelectedItem).HeaderContent.TabTitle.Content+"*";
        //    ((DocumentTab)TabCell.SelectedItem).HeaderContent.TabTitleFileChanged.Visibility = Visibility.Visible;
        //}
        //else
        //{
        //    Title = SelectedDocument.DocName + " - " + (My.MyWpfExtension.Application.Info.ProductName);
        //    ((DocumentTab)TabCell.SelectedItem).HeaderContent.TabTitle.Visibility = System.Windows.Visibility.Visible;
        //    ((DocumentTab)TabCell.SelectedItem).HeaderContent.TabTitleFileChanged.Visibility = Visibility.Collapsed;
        //}
        //MainBar.Title = Title;

        if (My.MyWpfExtension.Computer.Clipboard.ContainsText())
        {
            CommonPasteButton.IsEnabled = true;
            CommonPasteButton.ToolTipFooterTitle = "Preview:";
            CommonPasteButton.ToolTipFooterDescription = My.MyWpfExtension.Computer.Clipboard.GetText();
            PasteButton.IsEnabled = true;
            PasteButton.ToolTipFooterTitle = "Preview:";
            PasteButton.ToolTipFooterDescription = My.MyWpfExtension.Computer.Clipboard.GetText();
            PasteTextButton.IsEnabled = true;
        }
        else if (My.MyWpfExtension.Computer.Clipboard.ContainsImage())
        {
            //TODO: add paste image support
        }
        else
        {
            PasteTextButton.IsEnabled = false;
            CommonPasteButton.IsEnabled = false;
            CommonPasteButton.ToolTipFooterTitle = null;
            CommonPasteButton.ToolTipFooterDescription = null;
            PasteButton.IsEnabled = false;
            PasteButton.ToolTipFooterTitle = null;
            PasteButton.ToolTipFooterDescription = null;
        }
        if (SelectedDocument.Editor.teachingPlan.FileChanged)
        {
            SaveMenuItem.IsEnabled = true;
            SaveButton.IsEnabled = true;
        }
        else
        {
            //HungNQ 
            //SaveMenuItem.IsEnabled = false;
            //SaveButton.IsEnabled = false;
            SaveMenuItem.IsEnabled = true;
            SaveButton.IsEnabled = true;
        }

        if (layoutTeachingPlan.IsVisible)
        {
            CommonDeleteButton.CommandTarget = this.SelectedDocument.Editor.editor;
            DeleteButton.CommandTarget = this.SelectedDocument.Editor.editor;
            UndoButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonUndoButton.CommandTarget = this.SelectedDocument.Editor.editor;
            RedoButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonRedoButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CutButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonCutButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CopyButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonCopyButton.CommandTarget = this.SelectedDocument.Editor.editor;
            PasteButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonPasteButton.CommandTarget = this.SelectedDocument.Editor.editor;
            SelectAllButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonSelectAllButton.CommandTarget = this.SelectedDocument.Editor.editor;
            BoldButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonBoldButton.CommandTarget = this.SelectedDocument.Editor.editor;
            ItalicButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonItalicButton.CommandTarget = this.SelectedDocument.Editor.editor;
            UnderlineButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonUnderlineButton.CommandTarget = this.SelectedDocument.Editor.editor;
            IndentMoreButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonIndentMoreButton.CommandTarget = this.SelectedDocument.Editor.editor;
            IndentLessButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonIndentLessButton.CommandTarget = this.SelectedDocument.Editor.editor;
            BulletListButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonBulletListButton.CommandTarget = this.SelectedDocument.Editor.editor;
            NumberListButton.CommandTarget = this.SelectedDocument.Editor.editor;
            CommonNumberListButton.CommandTarget = this.SelectedDocument.Editor.editor;
            AlignJustifyButton.CommandTarget = this.SelectedDocument.Editor.editor;
            AlignRightButton.CommandTarget = this.SelectedDocument.Editor.editor;
            AlignCenterButton.CommandTarget = this.SelectedDocument.Editor.editor;
            AlignLeftButton.CommandTarget = this.SelectedDocument.Editor.editor;
            SuperscriptButton.CommandTarget = this.SelectedDocument.Editor.editor;
            SubscriptButton.CommandTarget = this.SelectedDocument.Editor.editor;
        }

    }

    private void UpdateButtons(object sender, RoutedEventArgs routedEventArgs)
    {
        if (TabCell.SelectedIndex != -1)
        {
            UpdateSelected();
            foreach (DocumentTab i in TabCell.Items)
            {
                i.ShowCloseButton();
            }
            if (layoutTeachingPlan.IsVisible)
            {
                ExportMenuItem.IsEnabled = true;
                //PropertiesMenuItem.IsEnabled = true;
                CloseMenuItem.IsEnabled = true;
                CloseAllMenuItem.IsEnabled = true;
                CloseAllButton.IsEnabled = true;
                SaveAsMenuItem.IsEnabled = true;
                SaveAsButton.IsEnabled = true;
                SaveAllMenuItem.IsEnabled = true;
                ExportButton.IsEnabled = true;
                SaveAllButton.IsEnabled = true;
            }
            EditTab.IsEnabled = true;
            InsertTab.IsEnabled = true;
            FormatTab.IsEnabled = true;
            CommonEditGroup.IsEnabled = true;
            CommonInsertGroup.IsEnabled = true;
            CommonFormatGroup.IsEnabled = true;
            CommonSpellCheckButton.IsEnabled = true;
            SpellCheckButton.IsEnabled = true;

        }
        else if (TabCell.SelectedIndex == -1)
        {
            SelectedDocument = null;
            Title = My.MyWpfExtension.Application.Info.ProductName;
            MainBar.Title = My.MyWpfExtension.Application.Info.ProductName;

            MainBar.SelectedIndex = 0;
            CloseMenuItem.IsEnabled = false;
            CloseAllMenuItem.IsEnabled = false;
            CloseAllButton.IsEnabled = false;
            SaveMenuItem.IsEnabled = false;
            SaveButton.IsEnabled = false;
            SaveAsMenuItem.IsEnabled = false;
            SaveAsButton.IsEnabled = false;
            SaveAllMenuItem.IsEnabled = false;
            SaveAllButton.IsEnabled = false;
            ExportButton.IsEnabled = false;
            ExportMenuItem.IsEnabled = false;
            //PropertiesMenuItem.IsEnabled = false;
            EditTab.IsEnabled = false;
            InsertTab.IsEnabled = false;
            FormatTab.IsEnabled = false;
            CommonPasteButton.ToolTipFooterTitle = null;
            CommonPasteButton.ToolTipFooterDescription = null;
            CommonEditGroup.IsEnabled = false;
            CommonInsertGroup.IsEnabled = false;
            CommonFormatGroup.IsEnabled = false;
            CommonSpellCheckButton.IsEnabled = false;
            SpellCheckButton.IsEnabled = false;

        }

    }

    #endregion

    #endregion

    #region MainWindow

    #region Add Handlers

    private void Addhandlers()
    {

        this.AddHandler(TabHeader.CloseTabEvent, new RoutedEventHandler(CloseDoc));
        this.AddHandler(TabHeader.SaveTabEvent, new RoutedEventHandler(SaveMenuItem_Click));
        this.AddHandler(TabHeader.SaveAsTabEvent, new RoutedEventHandler(SaveAsMenuItem_Click));
        this.AddHandler(RichTextEditor.UpdateSelected, new RoutedEventHandler(UpdateButtons));
        this.AddHandler(TeachingPlanDocument.FileChangedEvent, new RoutedEventHandler(FileChangedEventHandler));
        //this.AddHandler(RichTextEditor.UndoEvent, new RoutedEventHandler(UndoMenuItem_Click));
        //this.AddHandler(RichTextEditor.RedoEvent, new RoutedEventHandler(RedoMenuItem_Click));
        //this.AddHandler(RichTextEditor.CutEvent, new RoutedEventHandler(CutMenuItem_Click));
        //this.AddHandler(RichTextEditor.CopyEvent, new RoutedEventHandler(CopyMenuItem_Click));
        //this.AddHandler(RichTextEditor.PasteEvent, new RoutedEventHandler(PasteMenuItem_Click));
        //this.AddHandler(RichTextEditor.DeleteEvent, new RoutedEventHandler(DeleteMenuItem_Click));
        //this.AddHandler(RichTextEditor.SelectAllEvent, new RoutedEventHandler(SelectAllMenuItem_Click));
        //this.AddHandler(RichTextEditor.FindEvent, new RoutedEventHandler(FindButton_Click));
        //this.AddHandler(RichTextEditor.ReplaceEvent, new RoutedEventHandler(ReplaceButton_Click));
        //this.AddHandler(DocumentTab.GoToEvent, new RoutedEventHandler(GoToButton_Click));
    }

    private void FileChangedEventHandler(object sender, RoutedEventArgs e)
    {
        foreach (var tabItem in TabCell.Items)
        {
            var temp = (DocumentTab)tabItem;
            if (temp.Editor.teachingPlan.FileChanged)
            {
                temp.HeaderContent.TabTitle.Visibility = Visibility.Collapsed;
                temp.HeaderContent.TabTitleFileChanged.Content = temp.HeaderContent.TabTitle.Content + "*";
                temp.HeaderContent.TabTitleFileChanged.Visibility = Visibility.Visible;
            }
            else
            {
                temp.HeaderContent.TabTitle.Visibility = Visibility.Visible;
                temp.HeaderContent.TabTitleFileChanged.Visibility = Visibility.Collapsed;
            }
        }
        if (((DocumentTab)TabCell.SelectedItem).Editor.teachingPlan.FileChanged)
        {
            Title = SelectedDocument.DocName + " * - " + My.MyWpfExtension.Application.Info.ProductName;
        }
        else
        {
            Title = SelectedDocument.DocName + " - " + (My.MyWpfExtension.Application.Info.ProductName);
        }
        MainBar.Title = Title;
    }

    #endregion

    #region Activated

    public void MainWindow_Activated(object sender, System.EventArgs e)
    {

    }

    #endregion

    #region Key Down

    public void MainWindow_KeyDown(object sender, KeyEventArgs e)
    {
        if (TabCell.SelectedContent != null)
        {
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl) && !Keyboard.IsKeyDown(Key.LeftShift))
            {

                if (e.Key == Key.N)
                {
                    NewMenuItem_Click(null, null);
                }
                else if (e.Key == Key.O)
                {
                    e.Handled = true;
                    OpenMenuItem_Click(null, null);
                }

                else if (e.Key == Key.S)
                {
                    e.Handled = true;
                    if (SaveMenuItem.IsEnabled)
                    {
                        SaveMenuItem_Click(null, null);
                    }
                }
            }
            if (Keyboard.IsKeyDown(Key.Insert))
            {

                if (e.Key == Key.H)
                {
                    e.Handled = true;
                    HorizontalLineButton_Click(null, null);
                }
                else if (e.Key == Key.I)
                {
                    e.Handled = true;
                    ImageButton_Click(null, null);
                }

                else if (e.Key == Key.T)
                {
                    e.Handled = true;
                    TableButton_Click(null, null);
                }

                else if (e.Key == Key.X)
                {
                    e.Handled = true;
                    TextFileButton_Click(null, null);
                }
            }
            if (e.Key == Key.F1)
            {
                MainBar.SelectedIndex = 0;
            }
            else if (e.Key == Key.F2)
            {
                MainBar.SelectedIndex = 1;
            }
            else if (e.Key == Key.F3)
            {
                MainBar.SelectedIndex = 2;
            }
            else if (e.Key == Key.F4)
            {
                MainBar.SelectedIndex = 3;
            }
            else if (e.Key == Key.F5)
            {
                MainBar.SelectedIndex = 4;
            }
            else if (e.Key == Key.F6)
            {
                MainBar.SelectedIndex = 5;
            }
            else if (e.Key == Key.F7)
            {
                MainBar.SelectedIndex = 6;
            }
            else if (e.Key == Key.F8)
            {
                SpellCheckButton_Click(null, null);
            }

        }
        else
        {
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl) && !Keyboard.IsKeyDown(Key.LeftShift))
            {
                if (e.Key == Key.N)
                {
                    NewMenuItem_Click(null, null);
                }
                else if (e.Key == Key.O)
                {
                    e.Handled = true;
                    OpenMenuItem_Click(null, null);
                }
            }
            if (e.Key == Key.F1)
            {
                MainBar.SelectedIndex = 0;
            }
            else if (e.Key == Key.F6)
            {
                MainBar.SelectedIndex = 5;
            }
            else if (e.Key == Key.F7)
            {
                MainBar.SelectedIndex = 6;
            }
        }
    }

    #endregion

    #region Initialized

    public void MainWindow_Initialized(object sender, System.EventArgs e)
    {
        var t = new System.Threading.Thread(new ThreadStart(Addhandlers));

        t.Start();

        this.Show();
        //foreach (string file in (new Computer()).FileSystem.GetFiles(My.MyWpfExtension.Application.Info.DirectoryPath + "\\Templates\\"))
        //{
        //    var template = new System.IO.FileInfo(file);
        //    var item = new RibbonApplicationMenuItem();
        //    item.Header = template.Name.Remove(template.Name.Length - 5);
        //    item.ToolTipDescription = file;
        //    item.Click += new RoutedEventHandler(new RoutedEventHandler(NewFromTemplate));
        //    NewMenuItem.Items.Add(item);
        //}

    }

    #endregion

    #region Loaded

    public void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        if (Settings.Default.MainWindow_IsMax)
        {
            this.WindowState = WindowState.Maximized;
        }
        else
        {
            this.Left = Convert.ToDouble(Settings.Default.MainWindow_Loc.X);
            this.Top = Convert.ToDouble(Settings.Default.MainWindow_Loc.Y);
            this.Height = Convert.ToDouble(Settings.Default.MainWindow_Size.Height);
            this.Width = Convert.ToDouble(Settings.Default.MainWindow_Size.Width);
        }
        if (Settings.Default.MainWindow_HideRibbonbar)
        {
            MainBar.IsMinimized = true;
        }
        else
        {
            MainBar.IsMinimized = false;
        }
        if (Settings.Default.Options_ShowRecentDocuments && Settings.Default.Options_RecentFiles.Count > 0)
        {
            foreach (string s in Settings.Default.Options_RecentFiles)
            {
                if (My.MyWpfExtension.Computer.FileSystem.FileExists(s))
                {
                    var i2 = new RibbonApplicationMenuItem();
                    var f = new System.IO.FileInfo(s);
                    var ContMenu = new ContextMenu();
                    var removemenuitem = new MenuItem();
                    removemenuitem.Header = "Remove";
                    removemenuitem.ToolTip = f.FullName;
                    ContMenu.Items.Add(removemenuitem);
                    i2.ContextMenu = ContMenu;
                    i2.Header = f.Name;
                    i2.ToolTipTitle = f.Name;
                    i2.ToolTipDescription = s;
                    RecentFilesList.Children.Add(i2);
                    i2.Click += new RoutedEventHandler(new RoutedEventHandler(RecentfileClick));
                    removemenuitem.Click += new RoutedEventHandler(new RoutedEventHandler(RecentFileRemoveClick));
                }
            }
        }
        if (Settings.Default.MainWindow_QAToolbar_New)
        {
            ShowNewMenuItem.IsChecked = true;
            NewButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            ShowOpenMenuItem.IsChecked = false;
            NewButton.Visibility = System.Windows.Visibility.Collapsed;
        }
        if (Settings.Default.MainWindow_QAToolbar_Open)
        {
            ShowOpenMenuItem.IsChecked = true;
            OpenButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            ShowOpenMenuItem.IsChecked = false;
            OpenButton.Visibility = System.Windows.Visibility.Collapsed;
        }
        if (Settings.Default.MainWindow_QAToolbar_CloseAll)
        {
            ShowCloseAllMenuItem.IsChecked = true;
            CloseAllButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            ShowCloseAllMenuItem.IsChecked = false;
            CloseAllButton.Visibility = System.Windows.Visibility.Collapsed;
        }
        if (Settings.Default.MainWindow_QAToolbar_Save)
        {
            ShowSaveMenuItem.IsChecked = true;
            SaveButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            ShowSaveMenuItem.IsChecked = false;
            SaveButton.Visibility = System.Windows.Visibility.Collapsed;
        }
        if (Settings.Default.MainWindow_QAToolbar_SaveAs)
        {
            ShowSaveAsMenuItem.IsChecked = true;
            SaveAsButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            ShowSaveAsMenuItem.IsChecked = false;
            SaveAsButton.Visibility = System.Windows.Visibility.Collapsed;
        }
        if (Settings.Default.MainWindow_QAToolbar_SaveAll)
        {
            ShowSaveAllMenuItem.IsChecked = true;
            SaveAllButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            ShowSaveAllMenuItem.IsChecked = false;
            SaveAllButton.Visibility = System.Windows.Visibility.Collapsed;
        }
        if (Settings.Default.MainWindow_QAToolbar_Export)
        {
            ShowExportMenuItem.IsChecked = true;
            ExportButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            ShowExportMenuItem.IsChecked = false;
            ExportButton.Visibility = System.Windows.Visibility.Collapsed;
        }


        RibbonbarMenuItem.IsChecked = Convert.ToBoolean(Settings.Default.MainWindow_HideRibbonbar);
        if (Settings.Default.MainWindow_IsRibbonBelow)
        {
            MainMenuMenuItem.IsChecked = true;
            MainBar.ShowQuickAccessToolBarOnTop = false;
        }
        else
        {
            MainMenuMenuItem.IsChecked = false;
            MainBar.ShowQuickAccessToolBarOnTop = true;
        }

        try
        {
            if (Application.StartUpFileNames.Count > 0)
            {
                if (Settings.Default.Options_StartupMode == 1 && Settings.Default.Options_PreviousDocuments.Count > 0)
                {
                    CloseMenuItem_Click(this, null);
                    foreach (string s in Settings.Default.Options_PreviousDocuments)
                    {
                        if (My.MyWpfExtension.Computer.FileSystem.FileExists(s))
                        {
                            var f = new FileInfo(s);
                            NewDocument(f.Name);
                            SelectedDocument.Editor.LoadDocument(f.FullName);
                        }
                    }
                }
                foreach (string s in Application.StartUpFileNames)
                {
                    var f = new FileInfo(s);
                    NewDocument(f.Name);
                    SelectedDocument.Editor.LoadDocument(f.FullName);
                }
            }
            else
            {
                NewMenuItem_Click(this, null);
                if (Settings.Default.Options_StartupMode == 1 && Settings.Default.Options_PreviousDocuments.Count > 0)
                {
                    CloseMenuItem_Click(this, null);
                    foreach (string s in Settings.Default.Options_PreviousDocuments)
                    {
                        if (My.MyWpfExtension.Computer.FileSystem.FileExists(s))
                        {
                            var f = new System.IO.FileInfo(s);
                            NewDocument(f.Name);
                            SelectedDocument.Editor.LoadDocument(f.FullName);
                        }
                    }
                }
                else if (Settings.Default.Options_StartupMode == 2)
                {
                    CloseMenuItem_Click(this, null);
                    OpenMenuItem_Click(this, null);
                }
                else if (Settings.Default.Options_StartupMode == 3)
                {
                    CloseMenuItem_Click(this, null);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, ex.ToString());
        }

    }

    #endregion

    #region Closing

    public void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        while (TabCell.Items.Count > 0)
        {
            if (SelectedDocument.Editor.teachingPlan.FileChanged)
            {
                //HungNQ
                //var save = new SaveFileDialog();
                //save.Owner = this;
                //save.SetFileInfo(SelectedDocument.DocName, SelectedDocument.Editor);
                //System.IO.FileStream fs = System.IO.File.Open(My.MyWpfExtension.Computer.FileSystem.SpecialDirectories.Temp + "\\TVPre.xaml", System.IO.FileMode.Create);
                //var tr = new TextRange(SelectedDocument.Editor.editor.Document.ContentStart, SelectedDocument.Editor.editor.Document.ContentEnd);
                //System.Windows.Markup.XamlWriter.Save(SelectedDocument.Editor.editor.Document, fs);
                //fs.Close();
                Settings.Default.Options_PreviousDocuments.Clear();
                //save.ShowDialog();
                //if (save.Res.Equals("Yes"))
                //{
                //    if (SelectedDocument.Editor.DocumentName != null)
                //    {
                //        SelectedDocument.Editor.SaveDocument(SelectedDocument.Editor.DocumentName);
                //        Settings.Default.Options_PreviousDocuments.Add(SelectedDocument.Editor.DocumentName);
                //        CloseDocument(SelectedDocument);
                //    }
                //    else
                //    {
                //        SaveMenuItem_Click(null, null);
                //        if (SelectedDocument.Editor.DocumentName != null)
                //        {
                //            Settings.Default.Options_PreviousDocuments.Add(SelectedDocument.Editor.DocumentName);
                //        }
                //    }
                //}
                //else if (save.Res.Equals("No"))
                //{
                //    if (SelectedDocument.Editor.DocumentName != null)
                //    {
                //        Settings.Default.Options_PreviousDocuments.Add(SelectedDocument.Editor.DocumentName);
                //    }
                //    CloseDocument(SelectedDocument);
                //}
                //else
                //{
                //    e.Cancel = true;
                //    break;
                //}


                // Configure the message box to be displayed
                string messageBoxText = "";
                string caption = "";
                MessageBoxButton button = MessageBoxButton.YesNoCancel;
                MessageBoxImage icon = MessageBoxImage.Warning;
                var lang = cmbLanguage.SelectedValue.ToString();
                if (lang.Equals("en-US"))
                {
                    messageBoxText = "Do you want to save the changes you made to " + SelectedDocument.DocName + " ?";
                    caption = "Unsaved Changes";

                }
                else
                {
                    messageBoxText = "Bạn có muốn lưu thay đổi cho " + SelectedDocument.DocName + " ?";
                    caption = "Lưu thay đổi";
                }
                // Display message box
                MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

                // Process message box results
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        if (SelectedDocument.Editor.DocumentName != null)
                        {
                            SelectedDocument.Editor.SaveDocument();
                            Settings.Default.Options_PreviousDocuments.Add(SelectedDocument.Editor.DocumentName);
                            CloseDocument(SelectedDocument);
                        }
                        else
                        {
                            SaveMenuItem_Click(null, null);
                            if (SelectedDocument.Editor.DocumentName != null)
                            {
                                Settings.Default.Options_PreviousDocuments.Add(SelectedDocument.Editor.DocumentName);
                            }
                        }
                        break;
                    case MessageBoxResult.No:
                        if (SelectedDocument.Editor.DocumentName != null)
                        {
                            Settings.Default.Options_PreviousDocuments.Add(SelectedDocument.Editor.DocumentName);
                        }
                        CloseDocument(SelectedDocument);
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        return;

                }
            }
            else
            {
                if (SelectedDocument.Editor.DocumentName != null)
                {
                    Settings.Default.Options_PreviousDocuments.Add(SelectedDocument.Editor.DocumentName);
                }
                CloseDocument(SelectedDocument);
            }
        }

        if (this.WindowState == System.Windows.WindowState.Maximized)
        {
            Settings.Default.MainWindow_IsMax = true;
        }
        else if (this.WindowState == System.Windows.WindowState.Normal)
        {
            Settings.Default.MainWindow_IsMax = false;
            int width = Convert.ToInt32(this.ActualWidth);
            int height = Convert.ToInt32(this.ActualHeight);
            int left = Convert.ToInt32(Left);
            int top = Convert.ToInt32(Top);
            var s = new Size(width, height);
            var l = new Point(left, top);
            Settings.Default.MainWindow_Size = s;
            Settings.Default.MainWindow_Loc = l;
        }
        Settings.Default.MainWindow_HideRibbonbar = RibbonbarMenuItem.IsChecked;
        Settings.Default.MainWindow_QAToolbar_New = ShowNewMenuItem.IsChecked;
        Settings.Default.MainWindow_QAToolbar_Open = ShowOpenMenuItem.IsChecked;
        Settings.Default.MainWindow_QAToolbar_CloseAll = ShowCloseAllMenuItem.IsChecked;
        Settings.Default.MainWindow_QAToolbar_Save = ShowSaveMenuItem.IsChecked;
        Settings.Default.MainWindow_QAToolbar_SaveAs = ShowSaveAsMenuItem.IsChecked;
        Settings.Default.MainWindow_QAToolbar_SaveAll = ShowSaveAllMenuItem.IsChecked;
        Settings.Default.MainWindow_QAToolbar_Export = ShowExportMenuItem.IsChecked;

        if (Settings.Default.Options_StartupMode == 1 && Settings.Default.Options_PreviousDocuments.Count > 0)
        {
            Settings.Default.Options_PreviousDocuments.Clear();
        }


        Settings.Default.Save();

    }

    #endregion

    #endregion

    #region -QAToolbar

    public void ShowNewMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (ShowNewMenuItem.IsChecked)
        {
            NewButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            NewButton.Visibility = System.Windows.Visibility.Collapsed;
        }
    }

    public void ShowOpenMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (ShowOpenMenuItem.IsChecked)
        {
            OpenButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            OpenButton.Visibility = System.Windows.Visibility.Collapsed;
        }
    }

    public void ShowCloseAllMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (ShowCloseAllMenuItem.IsChecked)
        {
            CloseAllButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            CloseAllButton.Visibility = System.Windows.Visibility.Collapsed;
        }
    }

    public void ShowSaveMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (ShowSaveMenuItem.IsChecked)
        {
            SaveButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            SaveButton.Visibility = System.Windows.Visibility.Collapsed;
        }
    }

    public void ShowSaveAsMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (ShowSaveAsMenuItem.IsChecked)
        {
            SaveAsButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            SaveAsButton.Visibility = System.Windows.Visibility.Collapsed;
        }
    }

    public void ShowSaveAllMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (ShowSaveAllMenuItem.IsChecked)
        {
            SaveAllButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            SaveAllButton.Visibility = System.Windows.Visibility.Collapsed;
        }
    }

    public void ShowExportMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (ShowExportMenuItem.IsChecked)
        {
            ExportButton.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            ExportButton.Visibility = System.Windows.Visibility.Collapsed;
        }
    }



    public void MainMenuMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (MainMenuMenuItem.IsChecked)
        {
            Settings.Default.MainWindow_IsRibbonBelow = true;
            MainBar.ShowQuickAccessToolBarOnTop = false;
        }
        else
        {
            Settings.Default.MainWindow_IsRibbonBelow = false;
            MainBar.ShowQuickAccessToolBarOnTop = true;
        }
    }

    public void RibbonbarMenuItem_Click(System.Object sender, RoutedEventArgs e)
    {
        if (RibbonbarMenuItem.IsChecked)
        {
            MainBar.IsMinimized = true;
        }
        else
        {
            MainBar.IsMinimized = false;
        }
    }

    #endregion

    #region --DocumentMenu

    private void RecentfileClick(object sender, RoutedEventArgs e)
    {
        var menuItem = (RibbonApplicationMenuItem)e.Source;
        var f = new System.IO.FileInfo(menuItem.ToolTipDescription);
        if (f.Exists)
        {
            if (!filePaths.Contains(f.FullName))
            {
                
                NewDocument("");
                if (SelectedDocument.Editor.LoadDocument(f.FullName))
                {
                    SelectedDocument.HeaderContent.TabTitle.ToolTip = f.FullName;
                }else
                {
                    CloseDocument(SelectedDocument);
                }
                
            }
            else
            {
                for (int i = 0; i < TabCell.Items.Count; i++)
                {
                    var strTemp = ((DocumentTab)TabCell.Items[i]).Editor.FilePath;
                    if (strTemp != null && f.FullName.Equals(strTemp))
                    {
                        TabCell.SelectedIndex = i;
                        break;
                    }
                }
            }
        }
        else
        {
            if (_strLanguage.Equals("en-US"))
            {
                MessageBox.Show("File not found ! Please try another", "File Not Found !", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else
            {
                MessageBox.Show("Không tìm thấy tập tin ! Vui lòng thử tập tin khác", "Không tìm thấy tập tin !", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
    }

    private void RecentFileRemoveClick(object sender, RoutedEventArgs e)
    {
        var menuItem = (MenuItem)e.Source;
        RibbonApplicationMenuItem itemtoremove = null;
        foreach (RibbonApplicationMenuItem recentdoc in RecentFilesList.Children)
        {
            if (recentdoc.ToolTipDescription.Equals(menuItem.ToolTip))
            {
                itemtoremove = recentdoc;
            }
        }
        string stringToRemove = null;
        foreach (var s in Settings.Default.Options_RecentFiles)
        {
            if (s.Equals(menuItem.ToolTip))
            {
                stringToRemove = s;
            }
        }
        Settings.Default.Options_RecentFiles.Remove(stringToRemove);
        RecentFilesList.Children.Remove(itemtoremove);
    }

    #region New

    public void NewMenuItem_Click(System.Object sender, RoutedEventArgs e)
    {
        var num = TabCell.Items.Count;
        if (num < MAX_TAB)
        {
            //var genName = "New Document " + autoGenTabNumber++;
            NewDocument("New Document " + autoGenTabNumber++);
            SelectedDocument.Editor.teachingPlan.FileChanged = false;

        }
        else
        {
            _strLanguage = cmbLanguage.SelectedValue.ToString();
            MessageBox.Show(_strLanguage.Equals("en-US") ? "Can not create more tab" : "Không thể tạo thêm trang mới");
        }
    }

    //private void NewFromTemplate(object sender, RoutedEventArgs e)
    //{
    //    var ribbonApplicationMenuItem = (RibbonApplicationMenuItem)e.Source;
    //    var template = new System.IO.FileInfo(ribbonApplicationMenuItem.ToolTipDescription);
    //    var fs = new System.IO.FileStream(template.FullName, System.IO.FileMode.Open);
    //    var flowDocument = new FlowDocument();
    //    flowDocument = System.Windows.Markup.XamlReader.Load(fs) as FlowDocument;
    //    fs.Close();
    //    NewMenuItem_Click(null, null);
    //    SelectedDocument.Editor.editor.Document = flowDocument;//hainhCheck
    //    SelectedDocument.Editor.DocumentName = null;
    //    SelectedDocument.Editor.teachingPlan.FileChanged = false;
    //    e.Handled = true;
    //}
    //private void NewBlankDocument_Click(object sender, RoutedEventArgs e)
    //{
    //    var num = TabCell.Items.Count;
    //    if (num < MAX_TAB)
    //    {
    //        NewBlankDocument("Blank Document " + autoGenTabNumber++);
    //        SelectedDocument.Editor.teachingPlan.FileChanged = false;
    //    }
    //    else
    //    {
    //        _strLanguage = cmbLanguage.SelectedValue.ToString();
    //        MessageBox.Show(_strLanguage.Equals("en-US") ? "Can not create more tab" : "Không thể tạo thêm trang mới");
    //    }
    //}
    #endregion

    #region Open

    public void OpenMenuItem_Click(Object sender, RoutedEventArgs e)
    {

        //if (MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnVista || MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnWin7)
        //{
        try
        {
            var ofd = new OpenFileDialog
                          {
                              DefaultExt = ".tlhx",
                              Filter = "TeacherLeftHand Files (*.tlhx)|*.tlhx",
                              Multiselect = true
                          };
            if (ofd.ShowDialog() == true)
            {
                if (CoreHelpers.RunningOnWin7)
                {
                    TaskbarManager.Instance.SetOverlayIcon(My.Resources.Resources.open16, null);
                    TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);
                }
                //int itemcount = 0;
                //var load = new LoadFileDialog();
                int @int = 0;
                //foreach (string s in ofd.FileNames)
                //{
                //    itemcount++;
                //}
                this.IsEnabled = false;
                //load.Show();
                foreach (var filePath in ofd.FileNames)
                {
                    if (TabCell.Items.Count >= MAX_TAB)
                    {
                        MessageBox.Show(_strLanguage.Equals("en-US") ? "Can not create more tab" : "Không thể tạo thêm trang mới");
                        break;
                    }
                    var f = new System.IO.FileInfo(filePath);

                    if (!filePaths.Contains(filePath))
                        {


                            NewDocument(f.Name);

                            //SelectedDocument.Editor.FilePath = filePath;
                            if (SelectedDocument.Editor.LoadDocument(filePath))
                            {
                                //NewDocument(f.Name);
                                SelectedDocument.HeaderContent.TabTitle.ToolTip = filePath;
                                SelectedDocument.Editor.teachingPlan.FileChanged = false;
                                if (!Settings.Default.Options_RecentFiles.Contains(SelectedDocument.Editor.DocumentName) &&
                                    Settings.Default.Options_RecentFiles.Count < MAX_RECENT_FILES)
                                {
                                    Settings.Default.Options_RecentFiles.Add(SelectedDocument.Editor.DocumentName);
                                }
                                if (CoreHelpers.RunningOnWin7)
                                {
                                    TaskbarManager.Instance.SetProgressValue(@int, ofd.FileNames.Length);
                                    @int++;
                                }
                            }
                            else
                            {
                                CloseDocument(SelectedDocument);
                            }

                        }else
                        {
                            for (int i = 0; i < TabCell.Items.Count; i++)
                            {
                                var strTemp = ((DocumentTab)TabCell.Items[i]).Editor.FilePath;
                                if (strTemp != null && f.FullName.Equals(strTemp))
                                {
                                    TabCell.SelectedIndex = i;
                                    break;
                                }
                            }
                        }
                }
                this.IsEnabled = true;
                //load.flag = true;
                //load.Close();
                if (CoreHelpers.RunningOnWin7)
                {
                    TaskbarManager.Instance.SetOverlayIcon(null, null);
                    TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress);
                    TaskbarManager.Instance.TabbedThumbnail.InvalidateThumbnails();
                }

            }
        }
        catch (Exception ex)
        {
            Log.Debug("Error in MainWindow.cs - " + "OpenMenuItem_Click - " + ex.Message);
        }
        //}
        //else //Windows XP
        //{
        //var openfile = new OpenFileDialog
        //                   {
        //                       Multiselect = true,
        //                       Filter = "Supported Documents(.tlhx)|*.tlhx|All Files(.)|*."
        //                   };
        //if (openfile.ShowDialog() == true)
        //{
        //    var load = new LoadFileDialog();
        //    load.Show();
        //    foreach (string i in openfile.FileNames)
        //    {
        //        var f = new System.IO.FileInfo(i);
        //        NewDocument(f.Name);
        //        SelectedDocument.Editor.LoadDocument(f.FullName);
        //        SelectedDocument.Editor.teachingPlan.FileChanged = false;
        //        if (!Settings.Default.Options_RecentFiles.Contains(SelectedDocument.Editor.DocumentName))
        //        {
        //            Settings.Default.Options_RecentFiles.Add(SelectedDocument.Editor.DocumentName);
        //        }
        //    }
        //    load.flag = true;
        //    load.Close();
        //}

        //}

        /*Hainh
        //try
        //{
        //    var ofd = new OpenFileDialog { DefaultExt = ".tlhx", Filter = "TeacherLeftHand Files (*.tlhx)|*.tlhx" };
        //    if (ofd.ShowDialog() == true)
        //    {
        //        var filename = ofd.FileName;
        //        //SelectedDocument.SetDocumentTitle(Path.GetFileName(filename));
        //        //Read tlhx file
        //        LoadFile(filename);
        //    }
        //}
        //catch (Exception ex)
        //{
        //    Log.Debug("Error in MainWindow.cs - " + "OpenMenuItem_Click - " + ex.Message);
        //}
        */

    }


    //private void LoadFile(string filename)
    //{
    //    try
    //    {
    //        var teachingPlan = TeachingPlanAccessor.Load(filename);

    //        if (teachingPlan != null)
    //        {

    //            NewDocument(Path.GetFileName(filename));
    //            SelectedDocument.FilePath = filename;

    //            SelectedDocument.Editor.teachingPlan.dtpTPComposeDate.SelectedDate = teachingPlan.ComposeDate;
    //            SelectedDocument.Editor.teachingPlan.dtpTPTeachingDate.SelectedDate = teachingPlan.TeachingDate;
    //            SelectedDocument.Editor.teachingPlan.cmbTPClass.Text = teachingPlan.ClassLevel + "";
    //            SelectedDocument.Editor.teachingPlan.cmbTPSubject.Text = teachingPlan.Subject + "";
    //            SelectedDocument.Editor.teachingPlan.cmbTPTopic.Text = teachingPlan.Topic + "";
    //            SelectedDocument.Editor.teachingPlan.cmbTPTopicNumber.Text = teachingPlan.TopicNo + "";
    //            SelectedDocument.Editor.teachingPlan.tbxTPSessionNumber.Text = teachingPlan.Session + "";
    //            SelectedDocument.Editor.teachingPlan.tbxTPWeek.Text = teachingPlan.Week + "";
    //            SelectedDocument.Editor.teachingPlan.rtbObjective.Document =
    //                (FlowDocument)XamlReader.Load(new XmlTextReader(new StringReader((string)teachingPlan.Objective)));
    //            XMLUtilitizer.Transform64ToImage(SelectedDocument.Editor.teachingPlan.rtbObjective.Document);
    //            SelectedDocument.Editor.teachingPlan.rtbPreparation.Document =
    //               (FlowDocument)XamlReader.Load(new XmlTextReader(new StringReader((string)teachingPlan.Preparation)));
    //            XMLUtilitizer.Transform64ToImage(SelectedDocument.Editor.teachingPlan.rtbPreparation.Document);
    //            LoadActivity(teachingPlan.Activities);
    //            SelectedDocument.Editor.teachingPlan.rtbExperianceNote.Document =
    //                 (FlowDocument)XamlReader.Load(new XmlTextReader(new StringReader((string)teachingPlan.Note)));
    //            XMLUtilitizer.Transform64ToImage(SelectedDocument.Editor.teachingPlan.rtbExperianceNote.Document);

    //        }
    //    }
    //    catch (Exception ex)
    //    {

    //        Log.Debug("Error in MainWindow.cs - " + "LoadFile - " + ex.Message);
    //    }
    //}


    private void LoadActivity(List<Activity> lstActivity)
    {
        //try
        //{
        //    IEditableCollectionView items = SelectedDocument.Editor.listOfActivities.Items; //Cast to interface
        //    int act = 0;
        //    foreach (Activity activity in lstActivity)
        //    {
        //        if (items.CanAddNew)
        //        {
        //            items.AddNew();
        //            items.CommitNew();
        //            var activityItems = SelectedDocument.Editor.listOfActivities.Items;
        //            //for (int i = 0; i < activityItems.Count; i++)
        //            //{
        //                var activityView = activityItems.GetItemAt(act) as ActivityView;
        //                //ListView lvRtb = null;
        //            //IEnumerable<RichTextBox> lvRtb;

        //            var lstrtb = new ObservableCollection<RichTextBox>();

        //                if (activityView != null)
        //                {
        //                    activityView.rtbRtbActivityName.Text = activity.Name;
        //                    activityView.rtbPurpose.Text = activity.Purpose;
        //                    activityView.rtbMod.Text = activity.Form;
        //                    //var lstTM = activityView.listOfTeachingMethod;
        //                    foreach (var tm in activity.Content)
        //                    {
        //                        var rtbTm = new RichTextBox { Document = RichTextBoxProcessor.ConvertToFlowDocument(tm) ,MinWidth = 520};
        //                        //lvRtb = new RichTextBox[];
        //                        //lstrtb = new List<RichTextBox> {rtbTm};
        //                        lstrtb.Add(rtbTm);   
        //                    }
        //                    activityView.listOfTeachingMethod.ItemsSource = lstrtb ;   
        //                }
        //            //}
        //        }
        //        act++;
        //    }
        //}catch(Exception ex)
        //{
        //    Log.Debug("Error in MainWindow.cs - " + "LoadActivity - " + ex.Message);
        //}
        try
        {

            var listofActivity = new ObservableCollection<ActivityView>();
            foreach (Activity activity in lstActivity)
            {

                var activityView = new ActivityView();
                activityView.rtbRtbActivityName.Text = activity.Name;
                activityView.rtbPurpose.Text = activity.Purpose;
                activityView.rtbMod.Text = activity.Form;

                var lstrtb = new ObservableCollection<RichTextEditor>();
                //var lstrtb = new List<RichTextBox>();
                foreach (var tm in activity.Content)
                {
                    var rtbTm = new RichTextEditor { Width = 630, IsDocumentEnabled = true };
                    rtbTm.Document = (FlowDocument)XamlReader.Load(new XmlTextReader(new StringReader((string)tm)));
                    XMLUtilitizer.Transform64ToImage(rtbTm.Document);

                    lstrtb.Add(rtbTm);
                }
                activityView.listOfTeachingMethod.ItemsSource = lstrtb;
                listofActivity.Add(activityView);

            }
            SelectedDocument.Editor.teachingPlan.listOfActivities.ItemsSource = listofActivity;

        }
        catch (Exception ex)
        {
            Log.Debug("Error in MainWindow.cs - " + "LoadActivity - " + ex.Message);
        }



    }

    //private string test;

    #endregion

    #region Close/Close All

    public void CloseMenuItem_Click(Object sender, RoutedEventArgs e)
    {
        if (SelectedDocument.Editor.teachingPlan.FileChanged)//hainhCheck
        {
            //HungNQ 13/04/2012
            //var SaveDialog = new SaveFileDialog();
            //var tr = new TextRange(SelectedDocument.Editor.editor.Document.ContentStart, SelectedDocument.Editor.editor.Document.ContentEnd);
            //System.IO.FileStream fs = System.IO.File.Open(My.MyWpfExtension.Computer.FileSystem.SpecialDirectories.Temp + "\\TVPre.xaml", System.IO.FileMode.Create);
            //SaveDialog.Owner = this;
            //SaveDialog.SetFileInfo(SelectedDocument.DocName, SelectedDocument.Editor);
            //System.Windows.Markup.XamlWriter.Save(SelectedDocument.Editor.editor.Document, fs);
            //fs.Close();
            //SaveDialog.ShowDialog();
            var lang = cmbLanguage.SelectedValue.ToString();
            // Configure the message box to be displayed
            //MessageBox.Show(lang.Equals("en-US") ? "Export fail!" : "Xuất Giáo Án Thất Bại!");
            string messageBoxText = "";
            string caption = "";
            MessageBoxButton button = MessageBoxButton.YesNoCancel;
            MessageBoxImage icon = MessageBoxImage.Warning;

            if (lang.Equals("en-US"))
            {
                messageBoxText = "Do you want to save the changes you made to " + SelectedDocument.DocName + " ?";
                caption = "Unsaved Changes";

            }
            else
            {
                messageBoxText = "Bạn có muốn lưu thay đổi cho " + SelectedDocument.DocName + " ?";
                caption = "Lưu thay đổi";
            }
            // Display message box
            MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

            // Process message box results
            switch (result)
            {
                case MessageBoxResult.Yes:
                    SaveMenuItem_Click(null, null);
                    CloseDocument(SelectedDocument);
                    break;
                case MessageBoxResult.No:
                    CloseDocument(SelectedDocument);
                    break;
                case MessageBoxResult.Cancel:
                    break;
            }


            //if (SaveDialog.Res.Equals("Yes"))
            //{
            //    SaveMenuItem_Click(null, null);
            //    CloseDocument(SelectedDocument);
            //}
            //else if (SaveDialog.Res.Equals("No"))
            //{
            //    CloseDocument(SelectedDocument);
            //}
            //else if (SaveDialog.Res.Equals("Cancel"))
            //{
            //}
        }
        else
        {
            CloseDocument(SelectedDocument);
            //this.RemoveLogicalChild(SelectedDocument);
        }
    }

    public void CloseAllMenuItem_Click(object sender, RoutedEventArgs e)
    {
        while (TabCell.Items.Count > 0)
        {
            if (SelectedDocument.Editor.teachingPlan.FileChanged == true)//HainhCheck
            {
                //HungNQ 13/04/2012
                //var SaveDialog = new SaveFileDialog();
                //var tr = new TextRange(SelectedDocument.Editor.editor.Document.ContentStart, SelectedDocument.Editor.editor.Document.ContentEnd);
                //System.IO.FileStream fs = System.IO.File.Open(My.MyWpfExtension.Computer.FileSystem.SpecialDirectories.Temp + "\\TVPre.xaml", System.IO.FileMode.Create);
                //SaveDialog.SetFileInfo(SelectedDocument.DocName, SelectedDocument.Editor);
                //System.Windows.Markup.XamlWriter.Save(SelectedDocument.Editor.editor.Document, fs);
                //fs.Close();
                //SaveDialog.ShowDialog();
                //SaveDialog.Owner = this;
                //if (SaveDialog.Res.Equals("Yes"))
                //{
                //    SaveMenuItem_Click(this, null);
                //    CloseDocument(SelectedDocument);
                //}
                //else if (SaveDialog.Res.Equals("No"))
                //{
                //    CloseDocument(SelectedDocument);
                //}
                //else
                //{
                //    break;
                //}

                // Configure the message box to be displayed
                string messageBoxText = "";
                string caption = "";
                MessageBoxButton button = MessageBoxButton.YesNoCancel;
                MessageBoxImage icon = MessageBoxImage.Warning;
                var lang = cmbLanguage.SelectedValue.ToString();
                if (lang.Equals("en-US"))
                {
                    messageBoxText = "Do you want to save the changes you made to " + SelectedDocument.DocName + " ?";
                    caption = "Unsaved Changes";

                }
                else
                {
                    messageBoxText = "Bạn có muốn lưu thay đổi cho " + SelectedDocument.DocName + " ?";
                    caption = "Lưu thay đổi";
                }

                // Display message box
                MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

                // Process message box results
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        SaveMenuItem_Click(null, null);
                        CloseDocument(SelectedDocument);
                        break;
                    case MessageBoxResult.No:
                        CloseDocument(SelectedDocument);
                        break;
                    case MessageBoxResult.Cancel:
                        break;
                }

            }
            else
            {
                CloseDocument(SelectedDocument);
            }
        }
    }

    #endregion

    #region Save/Save As

    public void SaveMenuItem_Click(Object sender, RoutedEventArgs e)
    {
        if (SelectedDocument.Editor.FilePath == null)
        {
            SaveAsMenuItem_Click(this, null);
        }
        //else if (My.MyWpfExtension.Computer.FileSystem.FileExists(SelectedDocument.Editor.DocumentName))
        else
        {
            SelectedDocument.Editor.SaveDocument();
        }
        UpdateButtons(this, e);

        /*Hainh
        if (SelectedDocument.DocName.Contains("New Document"))
        {
            var sfd = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".tlhx", Filter = "TeacherLeftHand Files (*.tlhx)|*.tlhx" };
            if (sfd.ShowDialog() == true)
            {
                try
                {
                    var filename = sfd.FileName;
                    SelectedDocument.SetDocumentTitle(Path.GetFileName(filename));
                    SelectedDocument.FilePath = filename;
                    //SaveTeachingPlan tlhx file
                    //var teachingPlan = new TeachingPlan
                    //{
                    //    ClassLevel = SelectedDocument.Editor.teachingPlan.cmbTPClass.SelectedValue != null ? Convert.ToInt32(SelectedDocument.Editor.teachingPlan.cmbTPClass.SelectedValue.ToString()) : 1,
                    //    ComposeDate = SelectedDocument.Editor.teachingPlan.dtpTPComposeDate.SelectedDate != null ? SelectedDocument.Editor.teachingPlan.dtpTPComposeDate.SelectedDate.Value : (DateTime?)null,
                    //    TeachingDate = SelectedDocument.Editor.teachingPlan.dtpTPTeachingDate.SelectedDate != null ? SelectedDocument.Editor.teachingPlan.dtpTPTeachingDate.SelectedDate.Value : (DateTime?)null,
                    //    Subject = SelectedDocument.Editor.teachingPlan.cmbTPSubject.SelectedValue != null ? SelectedDocument.Editor.teachingPlan.cmbTPSubject.SelectedValue.ToString() : "",
                    //    Topic = SelectedDocument.Editor.teachingPlan.cmbTPSubject.SelectedValue != null ? SelectedDocument.Editor.teachingPlan.cmbTPSubject.SelectedValue.ToString() : "",
                    //    TopicNo = SelectedDocument.Editor.teachingPlan.cmbTPTopicNumber.SelectedValue != null ? Convert.ToInt32(SelectedDocument.Editor.teachingPlan.cmbTPTopicNumber.Text) : 0,
                    //    Session = String.IsNullOrEmpty(SelectedDocument.Editor.teachingPlan.tbxTPSessionNumber.Text) ? 0 : Convert.ToInt32(SelectedDocument.Editor.teachingPlan.tbxTPSessionNumber.Text.Trim()),
                    //    Week = String.IsNullOrEmpty(SelectedDocument.Editor.teachingPlan.tbxTPWeek.Text) ? 0 : Convert.ToInt32(SelectedDocument.Editor.teachingPlan.tbxTPWeek.Text),
                    //    Objective = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.teachingPlan.rtbObjective),
                    //    Preparation = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.teachingPlan.rtbPreparation),
                    //    //Activities = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.teachingPlan.rtbPreparation),
                    //    Activities = GetActivity("Save"),
                    //    Note = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.teachingPlan.rtbExperianceNote)
                    //};

                    Log.Debug(TeachingPlanAccessor.Save(filename, GetTeachingPlan("Save")) ? "SaveTeachingPlan succeed " : "SaveTeachingPlan failed ");
                    //test = XamlWriter.Save(SelectedDocument.Editor.teachingPlan);
                    //test = XamlWriter.Save(SelectedDocument.Editor.editor);
                    //Log.Debug(test);
                }
                catch (Exception ex)
                {
                    Log.Debug(ex.Message);
                }
            }
        }
        else
        {
            try
            {
                //SaveTeachingPlan tlhx file
                //var teachingPlan = new TeachingPlan
                //{
                //    ClassLevel = SelectedDocument.Editor.cmbTPClass.SelectedValue != null ? Convert.ToInt32(SelectedDocument.Editor.cmbTPClass.SelectedValue.ToString()) : 1,
                //    ComposeDate = SelectedDocument.Editor.dtpTPComposeDate.SelectedDate != null ? SelectedDocument.Editor.dtpTPComposeDate.SelectedDate.Value : (DateTime?)null,
                //    TeachingDate = SelectedDocument.Editor.dtpTPTeachingDate.SelectedDate != null ? SelectedDocument.Editor.dtpTPTeachingDate.SelectedDate.Value : (DateTime?)null,
                //    Subject = SelectedDocument.Editor.cmbTPSubject.SelectedValue != null ? SelectedDocument.Editor.cmbTPSubject.SelectedValue.ToString() : "",
                //    Topic = SelectedDocument.Editor.cmbTPSubject.SelectedValue != null ? SelectedDocument.Editor.cmbTPSubject.SelectedValue.ToString() : "",
                //    TopicNo = SelectedDocument.Editor.cmbTPTopicNumber.SelectedValue != null ? Convert.ToInt32(SelectedDocument.Editor.cmbTPTopicNumber.Text) : 0,
                //    Session = String.IsNullOrEmpty(SelectedDocument.Editor.tbxTPSessionNumber.Text) ? 0 : Convert.ToInt32(SelectedDocument.Editor.tbxTPSessionNumber.Text.Trim()),
                //    Week = String.IsNullOrEmpty(SelectedDocument.Editor.tbxTPWeek.Text) ? 0 : Convert.ToInt32(SelectedDocument.Editor.tbxTPWeek.Text),
                //    Objective = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.rtbObjective),
                //    Preparation = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.rtbPreparation),
                //    Activities = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.rtbPreparation),
                //    Note = RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.rtbExperianceNote)
                //};

                Log.Debug(TeachingPlanAccessor.Save(SelectedDocument.FilePath, GetTeachingPlan("Save")) ? "SaveTeachingPlan succeed " : "SaveTeachingPlan failed ");
            }
            catch (Exception ex)
            {
                Log.Debug(ex.Message);
            }
        }
        //MessageBox.Show(SelectedDocument.FilePath);
        */



    }

    public void SaveAsMenuItem_Click(Object sender, RoutedEventArgs e)
    {

        var sfd = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".tlhx", Filter = "TeacherLeftHand Files (*.tlhx)|*.tlhx" };
        if (sfd.ShowDialog() == true)
        {

            //var filename = sfd.FileName;
            //SelectedDocument.SetDocumentTitle(Path.GetFileName(filename));
            SelectedDocument.Editor.FilePath = sfd.FileName;
            SelectedDocument.Editor.SaveDocument();
            SelectedDocument.HeaderContent.TabTitle.ToolTip = sfd.FileName;
            //Log.Debug(TeachingPlanAccessor.Save(filename, GetTeachingPlan("SaveAs")) ? "SaveAs TeachingPlan succeed " : "SaveAs TeachingPlan failed ");
        }
        UpdateButtons(this, e);
        /* HungNQ
        if (MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnVista || MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnWin7)
        {
            var save = new CommonSaveFileDialog();
            var f = new CommonFileDialogFilter("FlowDocument", "*.xaml");
            var f2 = new CommonFileDialogFilter("Rich Text Document", "*.rtf");
            var f3 = new CommonFileDialogFilter("Text Document", "*.txt");
            var f4 = new CommonFileDialogFilter("All Files", "*.*");
            save.Filters.Add(f);
            save.Filters.Add(f2);
            save.Filters.Add(f3);
            save.Filters.Add(f4);
            if (save.ShowDialog() == CommonFileDialogResult.Ok)
            {
                if (save.SelectedFileTypeIndex == 1)
                {
                    // SelectedDocument.Editor.SaveDocument(save.FileName + ".xaml");
                }
                else if (save.SelectedFileTypeIndex == 2)
                {
                    //SelectedDocument.Editor.SaveDocument(save.FileName + ".rtf");
                }
                else if (save.SelectedFileTypeIndex == 3)
                {
                    // SelectedDocument.Editor.SaveDocument(save.FileName + ".txt");
                }
                else
                {
                    //SelectedDocument.Editor.SaveDocument(save.FileName);
                }
            }
        }
        else
        {
            var save = new Microsoft.Win32.SaveFileDialog();
            save.Filter = "FlowDocument(.xaml)|*.xaml|Rich Text Document(.rtf)|*.rtf|Text Document|*.txt|All Files(.)|*.*";
            if (save.ShowDialog() == true)
            {
                // SelectedDocument.Editor.SaveDocument(save.FileName);
            }
        }
        UpdateButtons(this, e);*/



    }

    #endregion

    #region Save All

    public void SaveAllMenuItem_Click(object sender, RoutedEventArgs e)
    {
        int @int = 0;
        if (CoreHelpers.RunningOnWin7)
        {
            TaskbarManager.Instance.SetOverlayIcon(My.Resources.Resources.save16, null);
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);
        }
        foreach (DocumentTab documentTab in TabCell.Items)
        {
            if (documentTab.Editor.DocumentName != null)
            {
                documentTab.Editor.SaveDocument();
            }
            else
            {

                documentTab.Focus();
                SaveAsMenuItem_Click(documentTab, null);
            }
            if (CoreHelpers.RunningOnWin7)
            {
                TaskbarManager.Instance.SetProgressValue(@int, TabCell.Items.Count);
                @int++;
            }
        }
        if (CoreHelpers.RunningOnWin7)
        {
            TaskbarManager.Instance.SetOverlayIcon(null, null);
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress);
        }
    }

    #endregion

    #region ---ExportMenuItem



    public List<Activity> GetActivity(string typeAction)
    {
        var lstActivity = new List<Activity>();
        for (int i = 0; i < SelectedDocument.Editor.teachingPlan.listOfActivities.Items.Count; i++)
        {
            var item = SelectedDocument.Editor.teachingPlan.listOfActivities.Items.GetItemAt(i);
            var activityView = item as ActivityView;
            if (activityView != null)
            {
                var lstTm = new List<object>();
                for (int j = 0; j < activityView.listOfTeachingMethod.Items.Count; j++)
                {
                    var richTextEditor = activityView.listOfTeachingMethod.Items.GetItemAt(j) as RichTextEditor;
                    if (richTextEditor != null)
                    {
                        //if (typeAction.Trim().Equals("Export"))
                        //{
                        var flowDocument = RichTextBoxProcessor.GetInlineText(richTextEditor, typeAction);
                        //}
                        //else
                        //{
                        //    //Clear Context Menu before save     
                        //    richTextEditor.ClearValue(RichTextEditor.ContextMenuProperty);
                        //    strTm = XMLUtilitizer.ConvertFlowDocumentToSUBStringFormat(richTextEditor.Document);
                        //}
                        //if (!string.IsNullOrEmpty(strTm))
                        //{
                        //    lstTm.Add(strTm);
                        //}
                        if (flowDocument != null)
                        {
                            lstTm.Add(flowDocument);
                        }
                    }
                }


                var activity = new Activity
                {
                    Name = (activityView).rtbRtbActivityName.Text,
                    Purpose = (activityView).rtbPurpose.Text,
                    Form = (activityView).rtbMod.Text,
                    Content = lstTm
                };
                if (!string.IsNullOrEmpty(activity.Name) || !string.IsNullOrEmpty(activity.Purpose) || !string.IsNullOrEmpty(activity.Form) || activity.Content.Count > 0)
                {
                    lstActivity.Add(activity);
                }

            }
        }

        return lstActivity;
    }

    private TeachingPlan GetTeachingPlan(string typeAction)
    {
        TeachingPlan teachingPlan = null;
        if (SelectedDocument != null)
        {
            teachingPlan = new TeachingPlan
            {
                ClassLevel = SelectedDocument.Editor.teachingPlan.cmbTPClass.SelectedValue != null ? Convert.ToInt32(SelectedDocument.Editor.teachingPlan.cmbTPClass.SelectedValue.ToString()) : 1,
                ComposeDate = SelectedDocument.Editor.teachingPlan.dtpTPComposeDate.SelectedDate != null ? SelectedDocument.Editor.teachingPlan.dtpTPComposeDate.SelectedDate.Value : (DateTime?)null,
                TeachingDate = SelectedDocument.Editor.teachingPlan.dtpTPTeachingDate.SelectedDate != null ? SelectedDocument.Editor.teachingPlan.dtpTPTeachingDate.SelectedDate.Value : (DateTime?)null,
                Subject = SelectedDocument.Editor.teachingPlan.cmbTPSubject.SelectedValue != null ? SelectedDocument.Editor.teachingPlan.cmbTPSubject.SelectedValue.ToString() : SelectedDocument.Editor.teachingPlan.cmbTPSubject.Text,
                //Topic = SelectedDocument.Editor.teachingPlan.cmbTPTopic.SelectedValue != null ? SelectedDocument.Editor.teachingPlan.cmbTPTopic.SelectedValue.ToString() : SelectedDocument.Editor.teachingPlan.cmbTPTopic.Text,
                Topic = SelectedDocument.Editor.teachingPlan.cmbTPTopic.Text,
                TopicNo = SelectedDocument.Editor.teachingPlan.cmbTPTopicNumber.Value != null ? SelectedDocument.Editor.teachingPlan.cmbTPTopicNumber.Value.Value : 0,
                Session = SelectedDocument.Editor.teachingPlan.tbxTPSessionNumber.Value == null ? 0 : SelectedDocument.Editor.teachingPlan.tbxTPSessionNumber.Value.Value,
                Week = SelectedDocument.Editor.teachingPlan.tbxTPWeek.Value == null ? 0 : SelectedDocument.Editor.teachingPlan.tbxTPWeek.Value.Value,
                //Objective =  RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.teachingPlan.rtbObjective),
                //Objective = typeAction.Trim().Equals("Export") ? RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.teachingPlan.rtbObjective) : XMLUtilitizer.ConvertFlowDocumentToSUBStringFormat(SelectedDocument.Editor.teachingPlan.rtbObjective.Document),
                //Preparation = typeAction.Trim().Equals("Export") ? RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.teachingPlan.rtbPreparation) : XMLUtilitizer.ConvertFlowDocumentToSUBStringFormat(SelectedDocument.Editor.teachingPlan.rtbPreparation.Document),
                Objective = Utility.CloneElement(SelectedDocument.Editor.teachingPlan.rtbObjective.Document),
                Preparation = Utility.CloneElement(SelectedDocument.Editor.teachingPlan.rtbPreparation.Document),
                Activities = GetActivity(typeAction),
                //Note = typeAction.Trim().Equals("Export") ? RichTextBoxProcessor.ConvertToString(SelectedDocument.Editor.teachingPlan.rtbExperianceNote) : XMLUtilitizer.ConvertFlowDocumentToSUBStringFormat(SelectedDocument.Editor.teachingPlan.rtbExperianceNote.Document)
                Note = Utility.CloneElement(SelectedDocument.Editor.teachingPlan.rtbExperianceNote.Document),
            };

            //return teachingPlan;
        }

        return teachingPlan;

    }

    #region Export Word

    private void ExportWordMenuItem_Click(object sender, RoutedEventArgs e)
    {
        string lang = cmbLanguage.SelectedValue.ToString();
        try
        {
            var sfd = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".doc", Filter = "Word 97-2003 Document (*.doc)|*.doc|Word Document (*.docx)|*.docx" };

            if (sfd.ShowDialog() == true)
            {

                progressBarWindow = new ProgressBarWindow();
                progressBarWindow.Owner = this;
                this.IsEnabled = false;
                progressBarWindow.Show();
                // end progress bar

                var filename = sfd.FileName;
                var fileType = Path.GetExtension(sfd.FileName);
                //lang { "en-US", ""vi-VN};
                

                //Export to Word);););
                if (TeachingPlanAccessor.ExportTeachingPlan(GetTeachingPlan("Export"), fileType, filename, lang))
                {
                    progressBarWindow.Close();
                    this.IsEnabled = true;
                    //Messenger.Default.Send("ProgressBarWindow.Close","ProgressBarWindow");
                    MessageBox.Show(lang.Equals("en-US") ? "Export completed!" : "Xuất Giáo Án Thành Công!");
                    Log.Debug("Export TeachingPlan'Word succeed ");
                    Process.Start("explorer.exe", "/select," + @filename);
                }
                else
                {
                    progressBarWindow.Close();
                    this.IsEnabled = true;
                    Messenger.Default.Send("ProgressBarWindow.Close", "ProgressBarWindow");
                    MessageBox.Show(lang.Equals("en-US") ? "Export fail!" : "Xuất Giáo Án Thất Bại!");
                    Log.Debug("Export TeachingPlan failed ");
                }
                Log.Debug(TeachingPlanAccessor.ExportTeachingPlan(GetTeachingPlan("Export"), fileType, filename, lang) ? "Export TeachingPlan succeed " : "Export TeachingPlan failed ");
            }
        }
        catch (Exception ex)
        {
            Log.Debug("MainWindow - Export word: " + ex.Message);
            progressBarWindow.Close();
            IsEnabled = true;
            MessageBox.Show(lang.Equals("en-US") ? "Export fail!" : "Xuất Giáo Án Thất Bại!");
        }


    }

    #endregion

    #region Export Rich Text Format

    private void ExportRTFMenuItem_Click(object sender, RoutedEventArgs e)
    {
        var sfd = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".rtf", Filter = "Rich Text Format (*.rtf)|*.rtf" };

        if (sfd.ShowDialog() == true)
        {
            var filename = sfd.FileName;
            var fileType = Path.GetExtension(sfd.FileName);
            //string lang = "en-EN";
            string lang = cmbLanguage.SelectedValue.ToString();
            //Export to RTF
            Log.Debug(TeachingPlanAccessor.ExportTeachingPlan(GetTeachingPlan("Export"), fileType, filename, lang) ? "Export TeachingPlan succeed " : "Export TeachingPlan failed ");
        }
    }

    #endregion

    #region Export PDF

    private void ExportPDFMenuItem_Click(object sender, RoutedEventArgs e)
    {
        string lang = cmbLanguage.SelectedValue.ToString();
        try
        {
            var sfd = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".pdf", Filter = "PDF Document (*.pdf)|*.pdf" };

            if (sfd.ShowDialog() == true)
            {
                progressBarWindow = new ProgressBarWindow();
                progressBarWindow.Owner = this;
                this.IsEnabled = false;
                progressBarWindow.Show();

                var filename = sfd.FileName;
                var fileType = Path.GetExtension(sfd.FileName);
                //string lang = "en-EN";
                
                //Export to XPS
                if (TeachingPlanAccessor.ExportTeachingPlan(GetTeachingPlan("Export"), fileType, filename, lang))
                {
                    Messenger.Default.Send(100, "ProgressBar");
                    progressBarWindow.Close();
                    this.IsEnabled = true;
                    MessageBox.Show(lang.Equals("en-US") ? "Export completed!" : "Xuất Giáo Án Thành Công!");
                    //MessageBox.Show("Export completed!");
                    Log.Debug("Export TeachingPlan's PDF succeed ");
                    //Process.Start("xpsrchvw.exe", @filename);
                    Process.Start("explorer.exe", "/select," + @filename);
                }
                else
                {
                    progressBarWindow.Close();
                    IsEnabled = true;
                    MessageBox.Show(lang.Equals("en-US") ? "Export fail!" : "Xuất Giáo Án Thất Bại!");
                    //MessageBox.Show("Export fail!");
                    Log.Debug("Export TeachingPlan'PDF failed ");
                }
                //Log.Debug(TeachingPlanAccessor.ExportTeachingPlan(GetTeachingPlan("Export"), fileType, filename, lang) ? "Export TeachingPlan succeed " : "Export TeachingPlan failed ");
            }


        }
        catch (Exception ex)
        {
            Log.Debug("MainWindow - Export PDF :" + ex.Message);
            progressBarWindow.Close();
            IsEnabled = true;
            MessageBox.Show(lang.Equals("en-US") ? "Export fail!" : "Xuất Giáo Án Thất Bại!");
        }
    }

    #endregion

    #region Export Xps

    public void ExportXPSMenuItem_Click(object sender, RoutedEventArgs e)
    {
        //if (MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnVista || MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnWin7)
        //{
        //    CommonSaveFileDialog save = new CommonSaveFileDialog();
        //    CommonFileDialogFilter f = new CommonFileDialogFilter("Xps Document", "*.xps");
        //    save.Filters.Add(f);
        //    if (save.ShowDialog() == CommonFileDialogResult.Ok)
        //    {
        //        System.Windows.Xps.Packaging.XpsDocument NewXpsDocument = new System.Windows.Xps.Packaging.XpsDocument(save.FileName + ".xps", System.IO.FileAccess.ReadWrite);
        //        System.Windows.Xps.XpsDocumentWriter xpsw = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(NewXpsDocument);
        //        xpsw.Write(SelectedDocument.Editor.editor);
        //        NewXpsDocument.Close();
        //        xpsw = null;
        //    }
        //}
        //else
        //{
        //    Microsoft.Win32.SaveFileDialog save = new Microsoft.Win32.SaveFileDialog();
        //    save.Filter = "Xps Document;*.xps";
        //    if (save.ShowDialog() == true)
        //    {
        //        System.Windows.Xps.Packaging.XpsDocument NewXpsDocument = new System.Windows.Xps.Packaging.XpsDocument(save.FileName + ".xps", System.IO.FileAccess.ReadWrite);
        //        System.Windows.Xps.XpsDocumentWriter xpsw = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(NewXpsDocument);
        //        xpsw.Write(SelectedDocument.Editor.editor);
        //        NewXpsDocument.Close();
        //        xpsw = null;
        //    }
        //}

        try
        {
            var sfd = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".xps", Filter = "XPS Document (*.xps)|*.xps" };

            if (sfd.ShowDialog() == true)
            {
                var filename = sfd.FileName;
                var fileType = Path.GetExtension(sfd.FileName);
                //string lang = "en-EN";
                string lang = cmbLanguage.SelectedValue.ToString();
                //Export to XPS
                if (TeachingPlanAccessor.ExportTeachingPlan(GetTeachingPlan("Export"), fileType, filename, lang))
                {
                    MessageBox.Show(lang.Equals("en-US") ? "Export completed!" : "Xuất Giáo Án Thành Công!");
                    //MessageBox.Show("Export completed!");
                    Log.Debug("Export TeachingPlan's XPS succeed ");
                    //Process.Start("xpsrchvw.exe", @filename);
                    Process.Start("explorer.exe", "/select," + @filename);
                }
                else
                {
                    MessageBox.Show(lang.Equals("en-US") ? "Export fail!" : "Xuất Giáo Án Thất Bại!");
                    //MessageBox.Show("Export fail!");
                    Log.Debug("Export TeachingPlan's XPS failed ");
                }
                //Log.Debug(TeachingPlanAccessor.ExportTeachingPlan(GetTeachingPlan("Export"), fileType, filename, lang) ? "Export TeachingPlan succeed " : "Export TeachingPlan failed ");
            }


        }
        catch (Exception ex)
        {
            Log.Debug("MainWindow - Export XPS :" + ex.Message);
        }

    }

    #endregion

    #endregion

    public void BackgroundColorMenuItem_Click(object sender, RoutedEventArgs e)
    {
        var d = new ColorDialog();
        d.Owner = this;
        if (d.ShowDialog() == true)
        {
            var b = new SolidColorBrush(d.SelectedColor);
            SelectedDocument.Editor.editor.Document.Background = b;
        }
    }



    public void ExitMenuItem_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }

    #endregion

    #region --EditMenu

    #region Undo/Redo/Cut/Copy/Paste/Delete/Select All

    //public void UndoMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        SelectedDocument.Editor.editor.Focus();
    //        SelectedDocument.Editor.editor.Undo();
    //    }

    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Focus();
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Undo();
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        layoutTeachingMethod.tmView.rtbContent.Focus();
    //        layoutTeachingMethod.tmView.rtbContent.Undo();
    //    }
    //}

    //public void RedoMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        SelectedDocument.Editor.editor.Focus();
    //        SelectedDocument.Editor.editor.Redo();
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Focus();
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Redo();
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        layoutTeachingMethod.tmView.rtbContent.Focus();
    //        layoutTeachingMethod.tmView.rtbContent.Redo();
    //    }
    //}

    //public void CutMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        SelectedDocument.Editor.editor.Focus();
    //        SelectedDocument.Editor.editor.Cut();
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Focus();
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Cut();
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        layoutTeachingMethod.tmView.rtbContent.Focus();
    //        layoutTeachingMethod.tmView.rtbContent.Cut();
    //    }
    //}

    public void CutParagraphMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            #region Editor

            try
            {
                if (SelectedDocument.Editor.editor.Selection.IsEmpty)
                {
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementStart,
                                                  SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            SelectedDocument.Editor.editor.Selection.Select(range.Start, range.End);
                            SelectedDocument.Editor.editor.Cut();
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, SelectedDocument.Editor.editor);
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementStart,
                                                  SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            SelectedDocument.Editor.editor.Selection.Select(range.Start, range.End);
                            SelectedDocument.Editor.editor.Cut();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;

            #endregion
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            #region KI Management

            try
            {
                if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.IsEmpty)
                {
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range =
                            new TextRange(
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementStart,
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.Select(range.Start, range.End);
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Cut();
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range =
                            new TextRange(
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementStart,
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.Select(range.Start, range.End);
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Cut();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;

            #endregion
        }
        if (layoutTeachingMethod.IsVisible)
        {
            #region TM Management

            try
            {
                if (layoutTeachingMethod.tmView.rtbContent.Selection.IsEmpty)
                {
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        var range =
                            new TextRange(layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementStart,
                                          layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Selection.Select(range.Start, range.End);
                            layoutTeachingMethod.tmView.rtbContent.Cut();
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, layoutTeachingMethod.tmView.rtbContent);
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        var range =
                            new TextRange(layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementStart,
                                          layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Selection.Select(range.Start, range.End);
                            layoutTeachingMethod.tmView.rtbContent.Cut();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;

            #endregion
        }
    }

    public void CutLineMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, SelectedDocument.Editor.editor);
            EditingCommands.SelectToLineEnd.Execute(null, SelectedDocument.Editor.editor);
            SelectedDocument.Editor.editor.Cut();
            e.Handled = true;
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            EditingCommands.SelectToLineEnd.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            SelectedDocument.Editor.editor.Cut();
            e.Handled = true;
        }
        if (layoutTeachingMethod.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            EditingCommands.SelectToLineEnd.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            SelectedDocument.Editor.editor.Cut();
            e.Handled = true;
        }
    }

    //public void CopyMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        SelectedDocument.Editor.editor.Focus();
    //        SelectedDocument.Editor.editor.Copy();
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Focus();
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Copy();
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        layoutTeachingMethod.tmView.rtbContent.Focus();
    //        layoutTeachingMethod.tmView.rtbContent.Copy();
    //    }
    //}

    public void CopyParagraphMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            #region teachingPlan

            try
            {
                if (SelectedDocument.Editor.editor.Selection.IsEmpty)
                {
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementStart,
                                                  SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            SelectedDocument.Editor.editor.Selection.Select(range.Start, range.End);
                            SelectedDocument.Editor.editor.Copy();
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, SelectedDocument.Editor.editor);
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementStart,
                                                  SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            SelectedDocument.Editor.editor.Selection.Select(range.Start, range.End);
                            SelectedDocument.Editor.editor.Copy();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;

            #endregion
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            #region Knowledge Item

            try
            {
                if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.IsEmpty)
                {
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range =
                            new TextRange(
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementStart,
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.Select(range.Start, range.End);
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Copy();
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range =
                            new TextRange(
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementStart,
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.Select(range.Start, range.End);
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Copy();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;

            #endregion
        }
        if (layoutTeachingMethod.IsVisible)
        {
            #region Teaching Method

            try
            {
                if (layoutTeachingMethod.tmView.rtbContent.Selection.IsEmpty)
                {
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        var range =
                            new TextRange(layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementStart,
                                          layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Selection.Select(range.Start, range.End);
                            layoutTeachingMethod.tmView.rtbContent.Copy();
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, layoutTeachingMethod.tmView.rtbContent);
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        var range =
                            new TextRange(layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementStart,
                                          layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Selection.Select(range.Start, range.End);
                            layoutTeachingMethod.tmView.rtbContent.Copy();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;

            #endregion
        }
    }

    public void CopyLineMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, SelectedDocument.Editor.editor);
            EditingCommands.SelectToLineEnd.Execute(null, SelectedDocument.Editor.editor);
            SelectedDocument.Editor.editor.Copy();
            e.Handled = true;
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            EditingCommands.SelectToLineEnd.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            SelectedDocument.Editor.editor.Copy();
            e.Handled = true;
        }
        if (layoutTeachingMethod.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            EditingCommands.SelectToLineEnd.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            SelectedDocument.Editor.editor.Copy();
            e.Handled = true;
        }
    }

    #region Paste

    //public void PasteMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        SelectedDocument.Editor.editor.Focus();
    //        SelectedDocument.Editor.editor.Paste();
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Focus();
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Paste();
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        layoutTeachingMethod.tmView.rtbContent.Focus();
    //        layoutTeachingMethod.tmView.rtbContent.Paste();
    //    }
    //}

    public void PasteTextButton_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            SelectedDocument.Editor.editor.CaretPosition.InsertTextInRun(Clipboard.GetText());
            e.Handled = true;
        }

        if (layoutKnowledgeItem.IsVisible)
        {
            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.InsertTextInRun(Clipboard.GetText());
            e.Handled = true;
        }
        if (layoutTeachingMethod.IsVisible)
        {
            layoutTeachingMethod.tmView.rtbContent.CaretPosition.InsertTextInRun(Clipboard.GetText());
            e.Handled = true;
        }
    }

    #endregion

    //public void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.Delete.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.Delete.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.Delete.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    public void DeleteParagraphMenuItem_Click(object sender, RoutedEventArgs e)
    {

        if (layoutTeachingPlan.IsVisible)
        {
            #region editor
            try
            {
                if (SelectedDocument.Editor.editor.Selection.IsEmpty)
                {
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementStart,
                                                  SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            SelectedDocument.Editor.editor.Selection.Select(range.Start, range.End);
                            EditingCommands.Delete.Execute(null, SelectedDocument.Editor.editor);
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, SelectedDocument.Editor.editor);
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementStart,
                                                  SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            SelectedDocument.Editor.editor.Selection.Select(range.Start, range.End);
                            EditingCommands.Delete.Execute(null, SelectedDocument.Editor.editor);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
            #endregion
        }


        if (layoutKnowledgeItem.IsVisible)
        {

            #region KnowledgeItem
            try
            {
                if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.IsEmpty)
                {
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementStart,
                                                  layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.Select(range.Start, range.End);
                            EditingCommands.Delete.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementStart,
                                                  layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.Select(range.Start, range.End);
                            EditingCommands.Delete.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
            #endregion
        }



        if (layoutTeachingMethod.IsVisible)
        {
            #region Teaching Method
            try
            {
                if (layoutTeachingMethod.tmView.rtbContent.Selection.IsEmpty)
                {
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementStart,
                                                  layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Selection.Select(range.Start, range.End);
                            EditingCommands.Delete.Execute(null, layoutTeachingMethod.tmView.rtbContent);
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, layoutTeachingMethod.tmView.rtbContent);
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementStart,
                                                  layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Selection.Select(range.Start, range.End);
                            EditingCommands.Delete.Execute(null, layoutTeachingMethod.tmView.rtbContent);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
            #endregion
        }


    }

    public void DeleteLineMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, SelectedDocument.Editor.editor);
            EditingCommands.SelectToLineEnd.Execute(null, SelectedDocument.Editor.editor);
            EditingCommands.Delete.Execute(null, SelectedDocument.Editor.editor);
            e.Handled = true;
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            EditingCommands.SelectToLineEnd.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            EditingCommands.Delete.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            e.Handled = true;
        }
        if (layoutTeachingMethod.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            EditingCommands.SelectToLineEnd.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            EditingCommands.Delete.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            e.Handled = true;
        }
    }


    //public void SelectAllMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        SelectedDocument.Editor.editor.Focus();
    //        SelectedDocument.Editor.editor.SelectAll();
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Focus();
    //        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.SelectAll();
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        layoutTeachingMethod.tmView.rtbContent.Focus();
    //        layoutTeachingMethod.tmView.rtbContent.SelectAll();
    //    }
    //}

    public void SelectParagraphMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            #region editor

            try
            {
                if (SelectedDocument.Editor.editor.Selection.IsEmpty)
                {
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementStart,
                                                  SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            SelectedDocument.Editor.editor.Selection.Select(range.Start, range.End);
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, SelectedDocument.Editor.editor);
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementStart,
                                                  SelectedDocument.Editor.editor.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            SelectedDocument.Editor.editor.Selection.Select(range.Start, range.End);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
            #endregion editor
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            #region KnowledgeItem

            try
            {
                if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.IsEmpty)
                {
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementStart,
                                                   layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.Select(range.Start, range.End);
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementStart,
                                                   layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.Select(range.Start, range.End);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
            #endregion editor
        }
        if (layoutTeachingMethod.IsVisible)
        {
            #region TeachingMethod

            try
            {
                if (layoutTeachingMethod.tmView.rtbContent.Selection.IsEmpty)
                {
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementStart,
                                                  layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Selection.Select(range.Start, range.End);
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, layoutTeachingMethod.tmView.rtbContent);
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementStart,
                                                  layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Selection.Select(range.Start, range.End);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
            #endregion editor
        }

    }

    public void SelectLineMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, SelectedDocument.Editor.editor);
            EditingCommands.SelectToLineEnd.Execute(null, SelectedDocument.Editor.editor);
            e.Handled = true;
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            EditingCommands.SelectToLineEnd.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
            e.Handled = true;
        }
        if (layoutTeachingMethod.IsVisible)
        {
            EditingCommands.MoveToLineStart.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            EditingCommands.SelectToLineEnd.Execute(null, layoutTeachingMethod.tmView.rtbContent);
            e.Handled = true;
        }
    }

    #endregion

    #region Find/Replace

    //public void FindButton_Click(object sender, RoutedEventArgs e)//hainhCheck
    //{
    //    var findDialog = new FindDialog(SelectedDocument.Editor.editor.Document);
    //    findDialog.Owner = this;
    //    findDialog.ShowDialog();
    //    if (findDialog.Res == "OK")
    //    {
    //        //var p = SelectedDocument.Editor.FindWordFromPosition(SelectedDocument.Editor.editor.CaretPosition, findDialog.TextBox1.Text);
    //        try
    //        {
    //            // SelectedDocument.Editor.editor.Selection.Select(p.Start, p.End);
    //        }
    //        catch (Exception)
    //        {
    //            MessageBox.Show("Word not found.");
    //        }
    //    }
    //}

    //public void ReplaceButton_Click(object sender, RoutedEventArgs e)//hainhCheck
    //{
    //    var replaceDialog = new ReplaceDialog();
    //    replaceDialog.Owner = this;
    //    replaceDialog.ShowDialog();
    //    if (replaceDialog.Res == "OK")
    //    {
    //        if (replaceDialog.TextBox1 != null)
    //        {
    //            //TextRange p = SelectedDocument.Editor.FindWordFromPosition(SelectedDocument.Editor.editor.Document.ContentStart.DocumentStart, (string)replaceDialog.TextBox1.Text);
    //            try
    //            {
    //                //SelectedDocument.Editor.editor.Selection.Select(p.Start, p.End);
    //                //SelectedDocument.Editor.editor.Selection.Text = (string)replaceDialog.TextBox2.Text;
    //            }
    //            catch (Exception)
    //            {
    //                MessageBox.Show("Word not found.");
    //            }
    //        }
    //    }
    //}

    //public void CommonReplaceButton_Click(object sender, RoutedEventArgs e)
    //{
    //    ReplaceButton_Click(null, null);
    //    e.Handled = true;
    //}

    #endregion

    //public void GoToButton_Click(object sender, RoutedEventArgs e)
    //{
    //    var gotodialog = new GoToDialog();
    //    gotodialog.Owner = this;
    //    gotodialog.ShowDialog();
    //    if (gotodialog.Res == "OK")
    //    {
    //        SelectedDocument.Editor.GoToLine(int.Parse(gotodialog.line));
    //    }
    //}
    //public void CommonGoToButton_Click(object sender, RoutedEventArgs e)
    //{
    //    GoToButton_Click(null, null);
    //    e.Handled = true;
    //}

    #endregion

    #region --ViewMenu


    //public void ZoomInButton_Click(object sender, RoutedEventArgs e)//hainhCheck
    //{
    //    SelectedDocument.Editor.ZoomLevel += 0.1;
    //    var layoutTransform = new ScaleTransform(SelectedDocument.Editor.ZoomLevel, SelectedDocument.Editor.ZoomLevel);
    //    SelectedDocument.Editor.editor.LayoutTransform = layoutTransform;
    //    UpdateButtons(this, e);

    //}

    //public void ZoomOutButton_Click(object sender, RoutedEventArgs e)
    //{
    //    SelectedDocument.Editor.ZoomLevel += -0.1;
    //    var layoutTransform = new ScaleTransform(SelectedDocument.Editor.ZoomLevel, SelectedDocument.Editor.ZoomLevel);
    //    SelectedDocument.Editor.editor.LayoutTransform = layoutTransform;
    //    UpdateButtons(this, e);

    //}

    //public void ResetZoomButton_Click(object sender, RoutedEventArgs e)
    //{
    //    SelectedDocument.Editor.ZoomLevel = 1;
    //    var layoutTransform = new ScaleTransform(SelectedDocument.Editor.ZoomLevel, SelectedDocument.Editor.ZoomLevel);
    //    SelectedDocument.Editor.editor.LayoutTransform = layoutTransform;
    //    UpdateButtons(null, null);

    //}

    private WindowState _fullscreensetting = System.Windows.WindowState.Normal;
    //public void FullScreenMenuItem_Click(object sender, RoutedEventArgs e)
    //{
    //    if (FullscreenMenuItem.IsPressed)
    //    {
    //        FullscreenMenuItem.IsChecked = false;
    //        Topmost = false;
    //        WindowStyle = System.Windows.WindowStyle.SingleBorderWindow;
    //        WindowState = _fullscreensetting;
    //    }
    //    else
    //    {
    //        FullscreenMenuItem.IsChecked = true;
    //        _fullscreensetting = WindowState;
    //        if (WindowState == System.Windows.WindowState.Maximized)
    //        {
    //            WindowState = System.Windows.WindowState.Normal;
    //        }
    //        WindowStyle = System.Windows.WindowStyle.None;
    //        Topmost = true;
    //        WindowState = System.Windows.WindowState.Maximized;
    //    }
    //}

    #endregion

    #region Image

    public void ImageButton_Click(object sender, RoutedEventArgs e)
    {
        var id = new ImageDialog();
        id.Owner = this;
        id.ShowDialog();
        if (id.Res == "OK")
        {
            #region teaching plan
            if (layoutTeachingPlan.IsVisible)
            {
                SelectedDocument.Editor.editor.Focus();
                foreach (var i in id.Images)
                {
                    //var caretPosition = SelectedDocument.Editor.editor.CaretPosition;
                    var caretPos = SelectedDocument.Editor.editor.CaretPosition;
                    var img = new Image();
                    var b = new BitmapImage();
                    b.BeginInit();
                    b.UriSource = new Uri(i);
                    b.EndInit();
                    img.Height = b.Height;
                    img.Width = b.Width;
                    img.Source = b;
                    img.Loaded += delegate
                                      {
                                          AdornerLayer al = AdornerLayer.GetAdornerLayer(img);
                                          if (al != null)
                                          {
                                              al.Add(new ResizingAdorner(img));
                                          }
                                      };
                    var inline = new InlineUIContainer(img, caretPos);

                }
            }
            #endregion teaching plan
            #region Knowledge item
            if (layoutKnowledgeItem.IsVisible)
            {
                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Focus();
                foreach (var i in id.Images)
                {
                    //var caretPosition = SelectedDocument.Editor.editor.CaretPosition;
                    var caretPos = layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition;
                    var img = new Image();
                    var b = new BitmapImage();
                    b.BeginInit();
                    b.UriSource = new Uri(i);
                    b.EndInit();
                    img.Height = b.Height;
                    img.Width = b.Width;
                    img.Source = b;
                    img.Loaded += delegate
                    {
                        AdornerLayer al = AdornerLayer.GetAdornerLayer(img);
                        if (al != null)
                        {
                            al.Add(new ResizingAdorner(img));
                        }
                    };
                    var inline = new InlineUIContainer(img, caretPos);

                }
            }
            #endregion knowledge item
            #region teaching method
            if (layoutTeachingMethod.IsVisible)
            {
                layoutTeachingMethod.tmView.rtbContent.Focus();
                foreach (var i in id.Images)
                {
                    //var caretPosition = SelectedDocument.Editor.editor.CaretPosition;
                    var caretPos = layoutTeachingMethod.tmView.rtbContent.CaretPosition;
                    var img = new Image();
                    var b = new BitmapImage();
                    b.BeginInit();
                    b.UriSource = new Uri(i);
                    b.EndInit();
                    img.Height = b.Height;
                    img.Width = b.Width;
                    img.Source = b;
                    img.Loaded += delegate
                    {
                        AdornerLayer al = AdornerLayer.GetAdornerLayer(img);
                        if (al != null)
                        {
                            al.Add(new ResizingAdorner(img));
                        }
                    };
                    var inline = new InlineUIContainer(img, caretPos);

                }
            }
            #endregion teaching method
        }
    }

    #endregion

    #region Link



    #endregion

    #region Text File

    public void TextFileButton_Click(object sender, RoutedEventArgs e)
    {


        if (MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnVista ||
            MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnWin7)
        {
            var o = new CommonOpenFileDialog();
            var f = new CommonFileDialogFilter("Text Document", "*.txt");
            o.Filters.Add(f);
            if (o.ShowDialog() == CommonFileDialogResult.Ok)
            {
                if (layoutTeachingPlan.IsVisible)
                {
                    SelectedDocument.Editor.editor.CaretPosition.InsertTextInRun(
                        My.MyWpfExtension.Computer.FileSystem.ReadAllText(o.FileName));
                }
                if (layoutKnowledgeItem.IsVisible)
                {
                    layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.InsertTextInRun(
                        My.MyWpfExtension.Computer.FileSystem.ReadAllText(o.FileName));
                }
                if (layoutTeachingMethod.IsVisible)
                {
                    layoutTeachingMethod.tmView.rtbContent.CaretPosition.InsertTextInRun(
                        My.MyWpfExtension.Computer.FileSystem.ReadAllText(o.FileName));
                }

            }
        }
        else
        {
            var o = new OpenFileDialog();
            o.Filter = "Text Document|*.txt";
            if (o.ShowDialog() == true)
            {

                if (layoutTeachingPlan.IsVisible)
                {
                    SelectedDocument.Editor.editor.CaretPosition.InsertTextInRun(
                        My.MyWpfExtension.Computer.FileSystem.ReadAllText(o.FileName));
                }
                if (layoutKnowledgeItem.IsVisible)
                {
                    layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.InsertTextInRun(
                        My.MyWpfExtension.Computer.FileSystem.ReadAllText(o.FileName));
                }
                if (layoutTeachingMethod.IsVisible)
                {

                    layoutTeachingMethod.tmView.rtbContent.CaretPosition.InsertTextInRun(
                        My.MyWpfExtension.Computer.FileSystem.ReadAllText(o.FileName));
                }
            }
        }


    }

    #endregion

    #region Table

    public void TableButton_Click(object sender, RoutedEventArgs e)
    {
        var tableDialog = new TableDialog();
        tableDialog.Owner = this;
        tableDialog.ShowDialog();
        if (tableDialog.Res == "OK")
        {
            var table = new Table();
            var rows = tableDialog.Rows;
            var cells = tableDialog.Cells;
            while (rows != 0)
            {
                var trg = new TableRowGroup();
                var tr = new TableRow();
                while (cells != 0)
                {
                    var tc = new TableCell();
                    if (tableDialog.BorderColor != null)
                    {
                        tc.BorderBrush = tableDialog.BorderColor;
                    }
                    else
                    {
                        tc.BorderBrush = Brushes.LightGray;
                    }
                    tc.BorderThickness = new Thickness(2, 2, 2, 2);
                    tr.Cells.Add(tc);
                    cells--;
                }
                cells = tableDialog.Cells;
                trg.Rows.Add(tr);
                table.RowGroups.Add(trg);
                rows--;
            }
            table.BorderBrush = Brushes.WhiteSmoke;

            try
            {
                #region teaching plan
                if (layoutTeachingPlan.IsVisible)
                {

                    if (SelectedDocument.Editor.editor.Document.Blocks.Count < 1)
                    {
                        SelectedDocument.Editor.editor.Document.Blocks.Add(new Paragraph());
                    }
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        if (SelectedDocument.Editor.editor.CaretPosition.Paragraph.PreviousBlock != null)
                        {
                            SelectedDocument.Editor.editor.Document.Blocks.InsertAfter(
                                SelectedDocument.Editor.editor.CaretPosition.Paragraph.PreviousBlock, table);
                        }
                        else if (SelectedDocument.Editor.editor.CaretPosition.Paragraph.SiblingBlocks != null)
                        {
                            SelectedDocument.Editor.editor.Document.Blocks.InsertAfter(
                                SelectedDocument.Editor.editor.CaretPosition.Paragraph.SiblingBlocks.FirstBlock, table);
                        }

                    }

                }
                #endregion
                #region knowledge item
                if (layoutKnowledgeItem.IsVisible)
                {
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Document.Blocks.Count < 1)
                    {
                        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Document.Blocks.Add(new Paragraph());
                    }
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.PreviousBlock != null)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Document.Blocks.InsertAfter(
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.PreviousBlock, table);
                        }
                        else if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.SiblingBlocks != null)
                        {
                            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Document.Blocks.InsertAfter(
                                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.SiblingBlocks.FirstBlock, table);
                        }

                    }
                }
                #endregion
                #region teachingmethod
                if (layoutTeachingMethod.IsVisible)
                {
                    if (layoutTeachingMethod.tmView.rtbContent.Document.Blocks.Count < 1)
                    {
                        layoutTeachingMethod.tmView.rtbContent.Document.Blocks.Add(new Paragraph());
                    }
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.PreviousBlock != null)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Document.Blocks.InsertAfter(
                                layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.PreviousBlock, table);
                        }
                        else if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.SiblingBlocks != null)
                        {
                            layoutTeachingMethod.tmView.rtbContent.Document.Blocks.InsertAfter(
                                layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.SiblingBlocks.FirstBlock, table);
                        }

                    }
                }
                #endregion
            }
            catch (Exception exception)
            {
                MessageBox.Show("Can not insert table");
            }

            UpdateButtons(this, e);
        }
    }

    #endregion

    #region Horizontal Line

    public void HorizontalLineButton_Click(object sender, RoutedEventArgs e)
    {
        var d = new InsertLineDialog();
        d.Owner = this;
        d.ShowDialog();
        if (d.Res == "OK")
        {
            var line = new Separator();
            var inline = new InlineUIContainer();
            line.Background = Brushes.Gray;
            line.Width = d.LineWidth;
            line.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            inline.Child = line;
            try
            {
                if (layoutTeachingPlan.IsVisible)
                {
                    if (SelectedDocument.Editor.editor.Document.Blocks.Count < 1)
                    {
                        SelectedDocument.Editor.editor.Document.Blocks.Add(new Paragraph());
                    }
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        SelectedDocument.Editor.editor.CaretPosition.Paragraph.Inlines.Add(inline);
                    }
                }
                if (layoutKnowledgeItem.IsVisible)
                {
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Document.Blocks.Count < 1)
                    {
                        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Document.Blocks.Add(new Paragraph());
                    }
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.Inlines.Add(inline);
                    }
                }
                if (layoutTeachingMethod.IsVisible)
                {
                    if (layoutTeachingMethod.tmView.rtbContent.Document.Blocks.Count < 1)
                    {
                        layoutTeachingMethod.tmView.rtbContent.Document.Blocks.Add(new Paragraph());
                    }
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.Inlines.Add(inline);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Can not insert line");
            }
        }
    }

    #endregion

    #region --FormatMenuItem

    public void ClearFormattingButton_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            SelectedDocument.Editor.editor.Selection.ClearAllProperties();
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.ClearAllProperties();
        }
        if (layoutTeachingMethod.IsVisible)
        {
            layoutTeachingMethod.tmView.rtbContent.Selection.ClearAllProperties();
        }
        UpdateSelected();
    }

    #region Font/Font Size/Font Color/Hightlight Color

    public void FontButton_Click(object sender, RoutedEventArgs e)
    {
        var d = new FontDialog();
        d.Owner = this;
        d.ShowDialog();
        if (d.Res == "OK")
        {
            if (layoutTeachingPlan.IsVisible)
            {
                if (SelectedDocument.Editor.editor.Selection != null)
                {
                    SelectedDocument.Editor.editor.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, d.font);
                }
            }
            if (layoutKnowledgeItem.IsVisible)
            {
                if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection != null)
                {
                    layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, d.font);
                }
            }
            if (layoutTeachingMethod.IsVisible)
            {
                if (layoutTeachingMethod.tmView.rtbContent.Selection != null)
                {
                    layoutTeachingMethod.tmView.rtbContent.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, d.font);
                }
            }
        }
    }

    public void FontSizeButton_Click(object sender, RoutedEventArgs e)
    {
        var d = new FontSizeDialog();
        d.Owner = this;
        d.ShowDialog();
        if (d.Res == "OK" && d.Number > 0)
        {
            if (layoutTeachingPlan.IsVisible)
            {
                SelectedDocument.Editor.editor.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, d.Number);
            }
            if (layoutKnowledgeItem.IsVisible)
            {
                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, d.Number);
            }
            if (layoutTeachingMethod.IsVisible)
            {
                layoutTeachingMethod.tmView.rtbContent.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, d.Number);
            }
        }
    }

    public void FontColorButton_Click(object sender, RoutedEventArgs e)
    {
        var d = new ColorDialog();
        var c = new SolidColorBrush();
        d.Owner = this;
        if (d.ShowDialog() == true)
        {
            c.Color = d.SelectedColor;
            if (layoutTeachingPlan.IsVisible)
            {
                SelectedDocument.Editor.editor.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, c);
            }
            if (layoutKnowledgeItem.IsVisible)
            {
                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, c);
            }
            if (layoutTeachingMethod.IsVisible)
            {
                layoutTeachingMethod.tmView.rtbContent.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, c);
            }
        }
    }

    public void HighlightColorButton_Click(object sender, RoutedEventArgs e)
    {
        var d = new ColorDialog();
        var c = new SolidColorBrush();
        d.Owner = this;
        if (d.ShowDialog() == true)
        {
            c.Color = d.SelectedColor;
            if (layoutTeachingPlan.IsVisible)
            {
                SelectedDocument.Editor.editor.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, c);
            }
            if (layoutKnowledgeItem.IsVisible)
            {
                layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, c);
            }
            if (layoutTeachingMethod.IsVisible)
            {
                layoutTeachingMethod.tmView.rtbContent.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, c);
            }
        }
    }

    #endregion

    #region Blod/Italic/Underline/Strikethrough

    //public void BoldMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.ToggleBold.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.ToggleBold.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.ToggleBold.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    //public void ItalicMenuItem_Click(object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.ToggleItalic.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.ToggleItalic.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.ToggleItalic.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    //public void UnderlineMenuItem_Click(object sender, RoutedEventArgs e)
    //{

    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.ToggleUnderline.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.ToggleUnderline.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.ToggleUnderline.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    public void StrikethroughButton_Click(object sender, RoutedEventArgs e)
    {
        //SelectedDocument.Editor.editor.ToggleStrikethrough();

        if (layoutTeachingPlan.IsVisible)
        {
            SelectedDocument.Editor.editor.ToggleStrikethrough();
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.ToggleStrikethrough();
        }
        if (layoutTeachingMethod.IsVisible)
        {
            layoutTeachingMethod.tmView.rtbContent.ToggleStrikethrough();
        }
    }

    #endregion



    //#region Indent More/Indent Less

    //public void IndentMoreButton_Click(object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.IncreaseIndentation.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.IncreaseIndentation.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.IncreaseIndentation.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }

    //}

    //public void IndentLessButton_Click(object sender, RoutedEventArgs e)
    //{

    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.DecreaseIndentation.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.DecreaseIndentation.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.DecreaseIndentation.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    //#endregion

    //#region Bullet List/Number List

    //public void BulletListMenuItem_Click(object sender, RoutedEventArgs e)
    //{

    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.ToggleBullets.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.ToggleBullets.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.ToggleBullets.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    //public void NumberListMenuItem_Click(object sender, RoutedEventArgs e)
    //{

    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.ToggleNumbering.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.ToggleNumbering.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.ToggleNumbering.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }

    //}

    //#endregion

    #region Align Left/Center/Right/Justify

    //public void AlignLeftMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{

    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.AlignLeft.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.AlignLeft.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.AlignLeft.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    //public void AlignCenterMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{

    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.AlignCenter.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.AlignCenter.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.AlignCenter.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    //public void AlignRightMenuItem_Click(System.Object sender, RoutedEventArgs e)
    //{

    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.AlignRight.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.AlignRight.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.AlignRight.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }
    //}

    //public void AlignJustifyMenuItem_Click(object sender, RoutedEventArgs e)
    //{
    //    if (layoutTeachingPlan.IsVisible)
    //    {
    //        EditingCommands.AlignJustify.Execute(null, SelectedDocument.Editor.editor);
    //    }
    //    if (layoutKnowledgeItem.IsVisible)
    //    {
    //        EditingCommands.AlignJustify.Execute(null, layoutKnowledgeItem.knowledgeItemView.rtbKIContent);
    //    }
    //    if (layoutTeachingMethod.IsVisible)
    //    {
    //        EditingCommands.AlignJustify.Execute(null, layoutTeachingMethod.tmView.rtbContent);
    //    }

    //}

    #endregion

    #region Line Spacing

    public void LineSpacingButton_Click(object sender, RoutedEventArgs e)
    {
        var d = new LineSpacingDialog();
        d.Owner = this;
        d.ShowDialog();
        if (d.Res == "OK")
        {
            try
            {
                if (layoutTeachingPlan.IsVisible)
                {
                    if (SelectedDocument.Editor.editor.CaretPosition.Paragraph != null)
                    {
                        SelectedDocument.Editor.editor.CaretPosition.Paragraph.LineHeight = d.number;
                    }
                }
                if (layoutKnowledgeItem.IsVisible)
                {
                    if (layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition.Paragraph.LineHeight = d.number;
                    }

                }
                if (layoutTeachingMethod.IsVisible)
                {
                    if (layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph != null)
                    {
                        layoutTeachingMethod.tmView.rtbContent.CaretPosition.Paragraph.LineHeight = d.number;
                    }
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Error");
            }
        }
    }

    #endregion

    #region ltr/rtl

    public void LefttoRightButton_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            SelectedDocument.Editor.editor.Document.FlowDirection = FlowDirection.LeftToRight;
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.Document.FlowDirection = FlowDirection.LeftToRight;
        }
        if (layoutTeachingMethod.IsVisible)
        {
            layoutTeachingMethod.tmView.rtbContent.Document.FlowDirection = FlowDirection.LeftToRight;
        }
    }

    public void RighttoLeftButton_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            SelectedDocument.Editor.editor.Document.FlowDirection = FlowDirection.RightToLeft;


        } if (layoutKnowledgeItem.IsVisible)
        {
            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.FlowDirection = FlowDirection.RightToLeft;
        } if (layoutTeachingMethod.IsVisible)
        {
            layoutTeachingMethod.tmView.rtbContent.FlowDirection = FlowDirection.RightToLeft;
        }
    }

    #endregion
    #region toogle
    private void SubscriptButton_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            SelectedDocument.Editor.editor.ToggleSubscript();
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.ToggleSubscript();
        }
        if (layoutTeachingMethod.IsVisible)
        {
            layoutTeachingMethod.tmView.rtbContent.ToggleSubscript();
        }

    }

    private void SuperscriptButton_Click(object sender, RoutedEventArgs e)
    {
        if (layoutTeachingPlan.IsVisible)
        {
            SelectedDocument.Editor.editor.ToggleSuperscript();
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            layoutKnowledgeItem.knowledgeItemView.rtbKIContent.ToggleSuperscript();
        }
        if (layoutTeachingMethod.IsVisible)
        {
            layoutTeachingMethod.tmView.rtbContent.ToggleSuperscript();
        }
    }
    #endregion toogle
    #endregion

    #region --ToolsMenuItem

    public void SpellCheckButton_Click(object sender, RoutedEventArgs e)
    {
        var d = new SpellCheckDialog();
        TextPointer caretPosition = null;
        if (layoutTeachingPlan.IsVisible)
        {
            caretPosition = SelectedDocument.Editor.editor.CaretPosition;
        }
        if (layoutKnowledgeItem.IsVisible)
        {
            caretPosition = layoutKnowledgeItem.knowledgeItemView.rtbKIContent.CaretPosition;
        }
        if (layoutTeachingMethod.IsVisible)
        {
            caretPosition = layoutTeachingMethod.tmView.rtbContent.CaretPosition;
        }
        d.Owner = this;
        if (caretPosition != null)
        {
            SpellingError sp = null;
            if (layoutTeachingPlan.IsVisible)
            {
                sp = SelectedDocument.Editor.editor.GetSpellingError(caretPosition);
            }
            if (layoutKnowledgeItem.IsVisible)
            {
                sp = layoutKnowledgeItem.knowledgeItemView.rtbKIContent.GetSpellingError(caretPosition);
            }
            if (layoutTeachingMethod.IsVisible)
            {
                sp = layoutTeachingMethod.tmView.rtbContent.GetSpellingError(caretPosition);
            }
            if (sp != null)
            {
                foreach (string i in sp.Suggestions)
                {
                    d.WordListBox.Items.Add(i);
                }
                d.WordListBox.SelectedIndex = 0;
                d.WordListBox.Focus();
            }
            d.ShowDialog();
            if (d.Res == "OK")
            {
                sp.Correct((string)d.WordListBox.SelectedItem);
            }
        }
    }

    #endregion

    #region TabCell

    private void CloseDoc(object sender, RoutedEventArgs e)
    {
        var tabHeader = (TabHeader)e.Source;
        var parent = (DocumentTab)tabHeader.Parent;
        if (parent.Editor.teachingPlan.FileChanged)
        {
            //var saveDialog = new SaveFileDialog();
            //System.IO.FileStream fs = System.IO.File.Open(My.MyWpfExtension.Computer.FileSystem.SpecialDirectories.Temp + "\\TVPre.xaml", System.IO.FileMode.Create);
            //var tr = new TextRange(parent.Editor.editor.Document.ContentStart, parent.Editor.editor.Document.ContentEnd);
            //saveDialog.Owner = this;
            //saveDialog.SetFileInfo(parent.DocName, parent.Editor);
            //System.Windows.Markup.XamlWriter.Save(parent.Editor.editor.Document, fs);
            //fs.Close();
            //saveDialog.ShowDialog();
            //if (saveDialog.Res.Equals("Yes"))
            //{
            //    SaveMenuItem_Click(this, null);
            //    CloseDocument(parent);
            //}
            //else if (saveDialog.Res.Equals("No"))
            //{
            //    CloseDocument(parent);
            //}

            // Configure the message box to be displayed
            string messageBoxText = "";
            string caption = "";
            MessageBoxButton button = MessageBoxButton.YesNoCancel;
            MessageBoxImage icon = MessageBoxImage.Warning;
            var lang = cmbLanguage.SelectedValue.ToString();
            if (lang.Equals("en-US"))
            {
                messageBoxText = "Do you want to save the changes you made to " + SelectedDocument.DocName + " ?";
                caption = "Unsaved Changes";

            }
            else
            {
                messageBoxText = "Bạn có muốn lưu thay đổi cho " + SelectedDocument.DocName + " ?";
                caption = "Lưu thay đổi";
            }

            // Display message box
            MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

            // Process message box results
            switch (result)
            {
                case MessageBoxResult.Yes:
                    SaveMenuItem_Click(null, null);
                    CloseDocument(parent);
                    break;
                case MessageBoxResult.No:
                    CloseDocument(parent);
                    break;
                case MessageBoxResult.Cancel:
                    break;
            }
        }
        else
        {
            CloseDocument(parent);
        }
    }

    DocumentTab t;
    int _oldPosition = -1;
    public void TabCell_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.Source.ToString() == "Document.Editor.TabHeader")
        {
            var h = (TabHeader)e.Source;
            t = (DocumentTab)h.Parent;
            object o = TabCell.ItemContainerGenerator.IndexFromContainer(h.Parent as DocumentTab);
            _oldPosition = short.Parse(o.ToString());
        }
    }

    public void TabCell_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        if (e.Source.ToString() == "Document.Editor.TabHeader")
        {
            var h = (TabHeader)e.Source;
            if (h.Parent != null)
            {
                object o = TabCell.ItemContainerGenerator.IndexFromContainer(h.Parent as DocumentTab);
                int i = short.Parse(o.ToString());
                if (o != null && _oldPosition != i)
                {
                    TabCell.Items.RemoveAt(_oldPosition);
                    TabCell.Items.Insert(i, t);
                    TabCell.SelectedItem = t;
                }
            }
        }
    }

    public void TabCell_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        //((TabItem)TabCell.Items.GetItemAt(1))

        if (TabCell.SelectedIndex == -1)
        {
            SelectedDocument = null;
            UpdateButtons(this, e);
        }
        else
        {
            filePaths.Clear();
            for (int i = 0; i < TabCell.Items.Count; i++)
            {
                var temp = (DocumentTab)TabCell.Items[i];
                if ((temp.Editor.FilePath) != null)
                {
                    filePaths.Add(temp.Editor.FilePath);
                }
                temp.HeaderContent.Background = Brushes.LightBlue;
            }
            SelectedDocument = (DocumentTab)TabCell.SelectedItem;
            SelectedDocument.HeaderContent.Background = Brushes.White;
            if (SelectedDocument.HeaderContent.TabTitle.Visibility == System.Windows.Visibility.Visible)
            {
                Title = SelectedDocument.HeaderContent.TabTitle.Content + " - " + My.MyWpfExtension.Application.Info.ProductName;
                MainBar.Title = SelectedDocument.HeaderContent.TabTitle.Content;
            }
            else
            {
                Title = SelectedDocument.HeaderContent.TabTitleFileChanged.Content + " - " + My.MyWpfExtension.Application.Info.ProductName;
                MainBar.Title = SelectedDocument.HeaderContent.TabTitleFileChanged.Content;
            }
            //new LinearGradientBrush { 
            //    StartPoint = new Point(0.9, 1), 
            //    EndPoint = new Point(0.1, 0.7),
            //    GradientStops = new GradientStopCollection { new GradientStop { Color = Colors.LightGreen }, new GradientStop{Color = Colors.LightBlue}}
            //};
            if (MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnWin7)
            {
                if (TaskbarManager.Instance.TabbedThumbnail.IsThumbnailPreviewAdded(SelectedDocument.Editor.editor))
                {
                    TaskbarManager.Instance.TabbedThumbnail.SetActiveTab(SelectedDocument.Editor.editor);
                }
            }

            UpdateButtons(this, e);
        }
    }

    #endregion

    #region Windows 7

    private void PreviewTabbedThumbnailMinimized(object sender, TabbedThumbnailEventArgs e)
    {
        this.WindowState = System.Windows.WindowState.Minimized;
    }

    private void PreviewTabbedThumbnailMaximized(object sender, TabbedThumbnailEventArgs e)
    {
        this.WindowState = System.Windows.WindowState.Maximized;
    }

    private void preview_TabbedThumbnailClosed(object sender, TabbedThumbnailClosedEventArgs e)//hainhCheck
    {
        var editor = (DocumentEditor)e.WindowsControl;
        var tab = (DocumentTab)editor.Parent;
        if (editor.teachingPlan.FileChanged)
        {
            //HungNQ
            //var s = new SaveFileDialog();
            //var fs = System.IO.File.Open(My.MyWpfExtension.Computer.FileSystem.SpecialDirectories.Temp + "\TVPre.xaml",
            //                             System.IO.FileMode.Create);
            //var tr = new TextRange(editor.editor.Document.ContentStart, editor.editor.Document.ContentEnd);
            //s.SetFileInfo(tab.DocName, editor);
            //            Markup.XamlWriter.Save(editor.Document, fs)
            //fs.Close();
            //s.ShowDialog();
            //if (s.Res.Equals("Yes"))
            //{
            //    SaveMenuItem_Click(this, null);
            //    CloseDocument(tab);
            //}
            //else if (s.Res.Equals("No"))
            //{
            //    CloseDocument(tab);
            //}
            //else
            //{
            //    e.Cancel = true;
            //}

            // Configure the message box to be displayed
            string messageBoxText = "";
            string caption = "";
            MessageBoxButton button = MessageBoxButton.YesNoCancel;
            MessageBoxImage icon = MessageBoxImage.Warning;
            var lang = cmbLanguage.SelectedValue.ToString();
            if (lang.Equals("en-US"))
            {
                messageBoxText = "Do you want to save the changes you made to " + SelectedDocument.DocName + " ?";
                caption = "Unsaved Changes";

            }
            else
            {
                messageBoxText = "Bạn có muốn lưu thay đổi cho " + SelectedDocument.DocName + " ?";
                caption = "Lưu thay đổi";
            }

            // Display message box
            MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

            // Process message box results
            switch (result)
            {
                case MessageBoxResult.Yes:
                    SaveMenuItem_Click(null, null);
                    CloseDocument(tab);
                    break;
                case MessageBoxResult.No:
                    CloseDocument(tab);
                    break;
                case MessageBoxResult.Cancel:
                    break;
            }

        }
        else
        {
            CloseDocument(tab);
        }
    }

    private void PreviewTabbedThumbnailActivated(object sender, TabbedThumbnailEventArgs e)
    {
        var editor = (DocumentEditor)e.WindowsControl;
        var tab = (DocumentTab)editor.Parent;
        TabCell.SelectedItem = tab;
        TaskbarManager.Instance.TabbedThumbnail.SetActiveTab(TaskbarManager.Instance.TabbedThumbnail.GetThumbnailPreview(editor));
        if (this.WindowState == WindowState.Minimized)
        {
            this.WindowState = WindowState.Normal;
        }
    }

    #endregion

    public void CloseAllButThisMenuItem_Click(object sender, RoutedEventArgs e)
    {
        //TODO:

    }

    #region Management

    //private TeachingMethodView ;
    private void TPManagementButton_Click(object sender, RoutedEventArgs e)
    {
        layoutTeachingPlan.Visibility = Visibility.Visible;
        layoutTeachingMethod.Visibility = Visibility.Collapsed;
        layoutKnowledgeItem.Visibility = Visibility.Collapsed;
        //KImanagement.Visibility = Visibility.Collapsed;
        //TMmanagement.Visibility = Visibility.Collapsed;
        radBtnTPHome.IsChecked = true;
        radBtnTPEdit.IsChecked = true;
        radBtnTPInsert.IsChecked = true;
        radBtnTPFormat.IsChecked = true;
        //radBtnTPTools.IsChecked = true;

        NewMenuItem.IsEnabled = true;
        //newBlankMenuItem.IsEnabled = true;
        NewButton.IsEnabled = true;
        OpenMenuItem.IsEnabled = true;
        CloseMenuItem.IsEnabled = true;
        CloseAllMenuItem.IsEnabled = true;
        CloseAllButton.IsEnabled = true;
        SaveMenuItem.IsEnabled = true;
        SaveButton.IsEnabled = true;
        SaveAsMenuItem.IsEnabled = true;
        SaveAsButton.IsEnabled = true;
        SaveAllMenuItem.IsEnabled = true;
        SaveAllButton.IsEnabled = true;
        ExportMenuItem.IsEnabled = true;
        ExportButton.IsEnabled = true;
        //PropertiesMenuItem.IsEnabled = true;

        //CommonDeleteButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //DeleteButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //UndoButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonUndoButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //RedoButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonRedoButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CutButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonCutButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CopyButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonCopyButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //PasteButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonPasteButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //SelectAllButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonSelectAllButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //BoldButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonBoldButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //ItalicButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonItalicButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //UnderlineButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonUnderlineButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //IndentMoreButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonIndentMoreButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //IndentLessButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonIndentLessButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //BulletListButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonBulletListButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //NumberListButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //CommonNumberListButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //AlignJustifyButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //AlignRightButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //AlignCenterButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //AlignLeftButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //SuperscriptButton.CommandTarget = this.SelectedDocument.Editor.editor;
        //SubscriptButton.CommandTarget = this.SelectedDocument.Editor.editor;
        CommonInsertGroup.Visibility = Visibility.Visible;
        InsertGroup.Visibility = Visibility.Visible;
        //CommonImageButton.Visibility = Visibility.Visible;
        //ImageButton.Visibility = Visibility.Visible;
        //CommonTableButton.Visibility = System.Windows.Visibility.Visible;
        //TableButton.Visibility = Visibility.Visible;
    }

    private void KIManagementButton_Click(object sender, RoutedEventArgs e)
    {
        // construct & destruct viewmodel
        ViewModelLocator.ClearTeachingMethodManage();
        layoutKnowledgeItem.DataContext = ViewModelLocator.KnowledgeItemManageStatic;

        layoutTeachingPlan.Visibility = Visibility.Collapsed;
        layoutTeachingMethod.Visibility = Visibility.Collapsed;
        layoutKnowledgeItem.Visibility = Visibility.Visible;

        //KImanagement.Visibility = Visibility.Visible;
        //TMmanagement.Visibility = Visibility.Collapsed;
        radBtnKIHome.IsChecked = true;
        radBtnKIEdit.IsChecked = true;
        radBtnKIInsert.IsChecked = true;
        radBtnKIFormat.IsChecked = true;
        //  radBtnKITools.IsChecked = true;

        NewMenuItem.IsEnabled = false;
        //newBlankMenuItem.IsEnabled = false;
        NewButton.IsEnabled = false;
        OpenMenuItem.IsEnabled = false;
        OpenButton.IsEnabled = false;
        CloseMenuItem.IsEnabled = false;
        CloseAllMenuItem.IsEnabled = false;
        CloseAllButton.IsEnabled = false;
        SaveMenuItem.IsEnabled = false;
        SaveButton.IsEnabled = false;
        SaveAsMenuItem.IsEnabled = false;
        SaveAsButton.IsEnabled = false;
        SaveAllMenuItem.IsEnabled = false;
        SaveAllButton.IsEnabled = false;
        ExportMenuItem.IsEnabled = false;
        ExportButton.IsEnabled = false;
        //PropertiesMenuItem.IsEnabled = false;

        CommonDeleteButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        DeleteButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        UndoButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonUndoButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        RedoButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonRedoButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CutButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonCutButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CopyButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonCopyButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        PasteButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonPasteButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        SelectAllButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonSelectAllButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        BoldButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonBoldButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        ItalicButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonItalicButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        UnderlineButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonUnderlineButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        IndentMoreButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonIndentMoreButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        IndentLessButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonIndentLessButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        BulletListButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonBulletListButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        NumberListButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        CommonNumberListButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        AlignJustifyButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        AlignRightButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        AlignCenterButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        AlignLeftButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        SuperscriptButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        SubscriptButton.CommandTarget = layoutKnowledgeItem.knowledgeItemView.rtbKIContent;
        //CommonImageButton.Visibility = Visibility.Visible;
        //ImageButton.Visibility = Visibility.Visible;
        //CommonTableButton.Visibility = System.Windows.Visibility.Visible;
        //TableButton.Visibility = Visibility.Visible;
        CommonInsertGroup.Visibility = Visibility.Visible;
        InsertGroup.Visibility = Visibility.Visible;
    }

    private void TMManagementButton_Click(object sender, RoutedEventArgs e)
    {
        // construct & deconstruct viewmodel 
        layoutTeachingMethod.DataContext = ViewModelLocator.TeachingMethodManageStatic;
        ViewModelLocator.ClearKnowledgeItemManage();

        layoutTeachingPlan.Visibility = Visibility.Collapsed;
        layoutTeachingMethod.Visibility = Visibility.Visible;
        layoutKnowledgeItem.Visibility = Visibility.Collapsed;
        //KImanagement.Visibility = Visibility.Collapsed;
        //TMmanagement.Visibility = Visibility.Visible;
        radBtnTMHome.IsChecked = true;
        radBtnTMEdit.IsChecked = true;
        radBtnTMInsert.IsChecked = true;
        radBtnTMFormat.IsChecked = true;
        //radBtnTMTools.IsChecked = true;

        NewMenuItem.IsEnabled = false;
        NewButton.IsEnabled = false;
        //newBlankMenuItem.IsEnabled = false;
        OpenMenuItem.IsEnabled = false;
        OpenButton.IsEnabled = false;
        CloseMenuItem.IsEnabled = false;
        CloseAllMenuItem.IsEnabled = false;
        CloseAllButton.IsEnabled = false;
        SaveMenuItem.IsEnabled = false;
        SaveButton.IsEnabled = false;
        SaveAsMenuItem.IsEnabled = false;
        SaveAsButton.IsEnabled = false;
        SaveAllMenuItem.IsEnabled = false;
        SaveAllButton.IsEnabled = false;
        ExportButton.IsEnabled = false;
        ExportMenuItem.IsEnabled = false;
        //PropertiesMenuItem.IsEnabled = false;

        CommonDeleteButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        DeleteButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        UndoButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonUndoButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        RedoButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonRedoButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CutButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonCutButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CopyButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonCopyButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        PasteButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonPasteButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        SelectAllButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonSelectAllButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        BoldButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonBoldButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        ItalicButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonItalicButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        UnderlineButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonUnderlineButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        IndentMoreButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonIndentMoreButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        IndentLessButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonIndentLessButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        BulletListButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonBulletListButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        NumberListButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        CommonNumberListButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        AlignJustifyButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        AlignRightButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        AlignCenterButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        AlignLeftButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        SuperscriptButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;
        SubscriptButton.CommandTarget = layoutTeachingMethod.tmView.rtbContent;

        //CommonImageButton.Visibility = Visibility.Hidden;
        //ImageButton.Visibility = Visibility.Hidden;
        //CommonTableButton.Visibility = System.Windows.Visibility.Hidden;
        //TableButton.Visibility = Visibility.Hidden;
        CommonInsertGroup.Visibility = Visibility.Collapsed;
        InsertGroup.Visibility = Visibility.Collapsed;
    }


    #endregion


}

